We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Elements With Maximum Frequency

Number: 3242

Difficulty: Easy

Paid? No

Companies: Amazon, Walmart Labs


Problem Description

Given an array of positive integers, determine the total frequencies (i.e., the sum of occurrences) of the elements that appear with the maximum frequency in the array. For instance, if an element appears 3 times and that is the maximum frequency among all elements, include all three occurrences in the total count.


Key Insights

  • Use a hash table (or dictionary) to count the frequency of each element.
  • Determine the maximum frequency value from the frequency counts.
  • Sum the counts of all elements whose frequency equals the maximum frequency.
  • The problem can be solved with a single or two-pass algorithm over the array.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), in the worst case when all elements are distinct.


Solution

We first traverse the array to build a frequency map using a hash table. Then, we determine the maximum frequency present in the map. Finally, we go through the map again to sum up the frequencies of the elements that match the maximum frequency. This method is efficient and directly uses counting and iteration, which is suitable given the constraints.


Code Solutions

# Function to count total frequencies of elements with maximum frequency
def count_max_frequency(nums):
    # Initialize a dictionary to count frequency of each element
    frequency = {}
    for num in nums:
        if num in frequency:
            frequency[num] += 1
        else:
            frequency[num] = 1

    # Get the maximum frequency from the dictionary values
    max_freq = max(frequency.values())

    # Sum the frequencies for elements that have the maximum frequency
    total_count = 0
    for count in frequency.values():
        if count == max_freq:
            total_count += count

    return total_count

# Example usage:
nums = [1, 2, 2, 3, 1, 4]
print(count_max_frequency(nums))  # Expected output: 4
← Back to All Questions