algoadvance

Given an integer array nums of length n, count the number of elements with the maximum frequency in the array.

Example

Input: nums = [1,2,2,3,3,3]
Output: 1
Explanation: The number 3 has the maximum frequency which is 3, and there is only one number with this frequency.

Clarifying Questions

  1. Can the input array be empty?
    • No, as per typical constraints, there must be at least one element in the array.
  2. Are there any constraints on the values within the array?
    • No specific constraints provided, so we can assume typical integer values within a reasonable range.
  3. What if multiple elements have the maximum frequency?
    • The task is to count how many unique elements have the maximum frequency.

Strategy

  1. Use a dictionary to count the frequency of each element in the array.
  2. Determine the maximum frequency from this dictionary.
  3. Count how many unique elements have this maximum frequency.

Code

def countMaxFrequencyElements(nums):
    # Step 1: Count the frequency of each element
    freq_count = {}
    for num in nums:
        if num in freq_count:
            freq_count[num] += 1
        else:
            freq_count[num] = 1
    
    # Step 2: Determine the maximum frequency
    max_freq = max(freq_count.values())
    
    # Step 3: Count how many elements have the maximum frequency
    max_freq_count = 0
    for count in freq_count.values():
        if count == max_freq:
            max_freq_count += 1
    
    return max_freq_count

# Test example from the problem statement
print(countMaxFrequencyElements([1, 2, 2, 3, 3, 3]))  # Output should be 1

Time Complexity

Thus, the overall time complexity is (O(n)).

Try our interview co-pilot at AlgoAdvance.com