#3005

Count Elements With Maximum Frequency

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we will use a hash map to count the frequencies of each element in a single pass. This allows us to efficiently find the maximum frequency and count the total occurrences of elements with that frequency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to store the frequency of each element.
  2. 2Step 2: Iterate through the array and populate the hash map with frequencies.
  3. 3Step 3: Determine the maximum frequency from the hash map.
  4. 4Step 4: Sum the frequencies of all elements that have the maximum frequency and return the total.
solution.py10 lines
1# Full working Python code
2
3def count_max_frequency(nums):
4    from collections import Counter
5    freq_map = Counter(nums)
6    max_freq = max(freq_map.values())
7    return sum(count for count in freq_map.values() if count == max_freq)
8
9# Example usage
10print(count_max_frequency([1, 2, 2, 3, 1, 4]))

Complexity note: The time complexity is O(n) because we only make a single pass through the array to count frequencies and another pass through the hash map to find the maximum frequency. The space complexity is O(n) due to the hash map storing frequencies.

  • 1Using a hash map allows for efficient frequency counting and retrieval.
  • 2The maximum frequency can be determined in a single pass after counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.