3005. Count Elements With Maximum Frequency
Problem Description
You are given an array nums
consisting of positive integers.
Your task is to find all elements that appear with the maximum frequency in the array, and return the sum of their frequencies.
The frequency of an element is the number of times it appears in the array.
For example:
- If
nums = [1, 2, 2, 3, 3]
, the frequencies are:1
appears once,2
appears twice, and3
appears twice. The maximum frequency is2
. Both2
and3
have this maximum frequency, so the total frequencies would be2 + 2 = 4
. - If
nums = [1, 2, 3, 4, 5]
, each element appears once (frequency of1
). Since all elements have the maximum frequency of1
, the total would be1 + 1 + 1 + 1 + 1 = 5
.
The solution uses a Counter
to track the frequency of each element, finds the maximum frequency value mx
, and then sums up all frequencies that equal mx
.
Intuition
To solve this problem, we need to identify which elements appear most frequently and then count their total occurrences.
The key insight is that we're looking for a two-step process:
- First, determine what the maximum frequency is across all elements
- Then, sum up the frequencies of all elements that have this maximum frequency
Think of it this way: if we have nums = [1, 2, 2, 3, 3, 3]
, we first count how many times each number appears:
1
appears1
time2
appears2
times3
appears3
times
The maximum frequency here is 3
. Only one element (3
) has this maximum frequency, so our answer is simply 3
.
But if we had nums = [1, 2, 2, 3, 3]
, both 2
and 3
appear 2
times (the maximum frequency). So we need to add up their frequencies: 2 + 2 = 4
.
This naturally leads us to use a counting structure (like Python's Counter
) to track frequencies, find the maximum value among all frequencies, and then sum up all frequency values that equal this maximum. The elegance of this approach is that it handles all cases uniformly - whether one element or multiple elements share the maximum frequency.
Solution Approach
The solution uses a counting approach with a hash table to efficiently track element frequencies.
Step 1: Count frequencies of all elements
We use Python's Counter
from the collections module to create a frequency map:
cnt = Counter(nums)
This creates a dictionary-like object where keys are the elements from nums
and values are their frequencies. For example, if nums = [1, 2, 2, 3, 3, 3]
, then cnt
would be {1: 1, 2: 2, 3: 3}
.
Step 2: Find the maximum frequency
We extract all frequency values and find the maximum:
mx = max(cnt.values())
The cnt.values()
gives us all the frequency counts, and max()
finds the highest frequency among them.
Step 3: Sum frequencies equal to maximum
We iterate through all frequency values and sum up those that equal the maximum frequency:
return sum(x for x in cnt.values() if x == mx)
This generator expression filters for frequencies equal to mx
and sums them up.
Time Complexity: O(n)
where n
is the length of the input array, as we traverse the array once to count frequencies and then traverse the frequency values (at most n
unique elements).
Space Complexity: O(n)
in the worst case when all elements are unique, requiring space to store each element's count in the hash table.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [4, 7, 7, 1, 1, 7]
.
Step 1: Count frequencies
We create a frequency map using Counter(nums)
:
4
appears 1 time7
appears 3 times1
appears 2 times
So cnt = {4: 1, 7: 3, 1: 2}
Step 2: Find maximum frequency
We get all frequency values: [1, 3, 2]
The maximum frequency is mx = 3
Step 3: Sum frequencies equal to maximum We check each frequency value:
- Is
1 == 3
? No, skip - Is
3 == 3
? Yes, include in sum - Is
2 == 3
? No, skip
Only the frequency 3
(from element 7
) equals the maximum, so our sum is 3
.
Result: The function returns 3
.
Let's trace through one more example where multiple elements share the maximum frequency:
nums = [5, 5, 8, 8, 9]
- Count:
{5: 2, 8: 2, 9: 1}
- Maximum frequency:
mx = 2
- Sum frequencies equal to max:
2
(from5
) +2
(from8
) =4
The function returns 4
because both 5
and 8
appear with the maximum frequency of 2
.
Solution Implementation
1from typing import List
2from collections import Counter
3
4class Solution:
5 def maxFrequencyElements(self, nums: List[int]) -> int:
6 # Count the frequency of each element in the array
7 frequency_counter = Counter(nums)
8
9 # Find the maximum frequency among all elements
10 max_frequency = max(frequency_counter.values())
11
12 # Calculate the sum of frequencies for all elements that have the maximum frequency
13 # This gives us the total count of elements with maximum frequency
14 total_count = sum(freq for freq in frequency_counter.values() if freq == max_frequency)
15
16 return total_count
17
1class Solution {
2 public int maxFrequencyElements(int[] nums) {
3 // Array to store frequency count of each element (elements range from 1 to 100)
4 int[] frequencyCount = new int[101];
5
6 // Count the frequency of each element in the input array
7 for (int num : nums) {
8 frequencyCount[num]++;
9 }
10
11 // Initialize variables to track the result and maximum frequency
12 int totalCount = 0;
13 int maxFrequency = -1;
14
15 // Iterate through frequency counts to find elements with maximum frequency
16 for (int frequency : frequencyCount) {
17 if (frequency > maxFrequency) {
18 // Found a new maximum frequency
19 maxFrequency = frequency;
20 totalCount = frequency; // Reset total count to this frequency
21 } else if (frequency == maxFrequency) {
22 // Found another element with the same maximum frequency
23 totalCount += frequency; // Add to the total count
24 }
25 }
26
27 // Return the total count of elements that have the maximum frequency
28 return totalCount;
29 }
30}
31
1class Solution {
2public:
3 int maxFrequencyElements(vector<int>& nums) {
4 // Array to store frequency count of each element (1 <= nums[i] <= 100)
5 int frequency[101] = {0};
6
7 // Count the frequency of each element in nums
8 for (int num : nums) {
9 ++frequency[num];
10 }
11
12 // Variables to track the result and maximum frequency
13 int totalCount = 0;
14 int maxFrequency = -1;
15
16 // Iterate through all frequencies to find elements with maximum frequency
17 for (int freq : frequency) {
18 if (maxFrequency < freq) {
19 // Found a new maximum frequency
20 maxFrequency = freq;
21 totalCount = freq; // Reset total count to this frequency
22 } else if (maxFrequency == freq) {
23 // Found another element with the same maximum frequency
24 totalCount += freq; // Add its frequency to the total
25 }
26 }
27
28 return totalCount;
29 }
30};
31
1/**
2 * Calculates the total frequency of elements that have the maximum frequency in the array
3 * @param nums - Array of numbers to analyze
4 * @returns The sum of frequencies of all elements that appear with maximum frequency
5 */
6function maxFrequencyElements(nums: number[]): number {
7 // Initialize frequency counter array for numbers 1-100
8 const frequencyCounter: number[] = Array(101).fill(0);
9
10 // Count frequency of each number in the input array
11 for (const num of nums) {
12 frequencyCounter[num]++;
13 }
14
15 // Track the sum of max frequencies and current max frequency
16 let totalMaxFrequency: number = 0;
17 let maxFrequency: number = -1;
18
19 // Iterate through frequency counter to find elements with max frequency
20 for (const frequency of frequencyCounter) {
21 if (frequency > maxFrequency) {
22 // Found new maximum frequency, reset the total
23 maxFrequency = frequency;
24 totalMaxFrequency = frequency;
25 } else if (frequency === maxFrequency) {
26 // Found another element with same max frequency, add to total
27 totalMaxFrequency += frequency;
28 }
29 }
30
31 return totalMaxFrequency;
32}
33
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the array nums
. This is because:
- Creating the Counter object requires iterating through all
n
elements once:O(n)
- Finding the maximum value among the frequencies using
max(cnt.values())
takesO(k)
wherek
is the number of unique elements, andk ≤ n
, so this isO(n)
in the worst case - The final sum operation iterates through all unique elements' frequencies, which is again
O(k)
wherek ≤ n
, giving usO(n)
- Overall:
O(n) + O(n) + O(n) = O(n)
The space complexity is O(n)
, where n
is the length of the array nums
. This is because:
- The Counter object
cnt
stores at mostn
key-value pairs (in the worst case where all elements are unique), requiringO(n)
space - The generator expression in the sum creates values on-the-fly without storing them, so it uses
O(1)
additional space - Overall:
O(n) + O(1) = O(n)
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Empty Array Handling
Pitfall: The code will raise a ValueError
when nums
is empty because max()
cannot operate on an empty sequence.
# This will fail if nums = []
max_frequency = max(frequency_counter.values()) # ValueError: max() arg is an empty sequence
Solution: Add a check for empty input:
def maxFrequencyElements(self, nums: List[int]) -> int:
if not nums: # Handle empty array
return 0
frequency_counter = Counter(nums)
max_frequency = max(frequency_counter.values())
total_count = sum(freq for freq in frequency_counter.values() if freq == max_frequency)
return total_count
2. Inefficient Double Iteration Over Values
Pitfall: The current solution iterates through frequency_counter.values()
twice - once to find the maximum and once to sum matching frequencies. This could be optimized to a single pass.
Solution: Use a single iteration approach:
def maxFrequencyElements(self, nums: List[int]) -> int:
if not nums:
return 0
frequency_counter = Counter(nums)
frequencies = list(frequency_counter.values())
max_frequency = frequencies[0]
total_count = frequencies[0]
for freq in frequencies[1:]:
if freq > max_frequency:
max_frequency = freq
total_count = freq # Reset count with new maximum
elif freq == max_frequency:
total_count += freq # Add to count if equal to maximum
return total_count
3. Misunderstanding the Problem Requirements
Pitfall: Some might mistakenly return just the count of distinct elements with maximum frequency rather than the sum of their frequencies.
# Wrong interpretation - returns count of distinct elements
return sum(1 for x in cnt.values() if x == mx) # This would return 2 for [1,2,2,3,3]
# Correct - returns sum of frequencies
return sum(x for x in cnt.values() if x == mx) # This returns 4 for [1,2,2,3,3]
4. Not Considering Integer Overflow (Language-Specific)
Pitfall: While Python handles arbitrary precision integers automatically, in other languages like Java or C++, summing large frequencies could cause integer overflow.
Solution for other languages: Use appropriate data types (e.g., long
in Java, long long
in C++) when dealing with potentially large sums.
Consider the classic dynamic programming of longest increasing subsequence:
Find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.
For example, the length of LIS for [50, 3, 10, 7, 40, 80]
is 4
and LIS is
[3, 7, 40, 80]
.
What is the recurrence relation?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!