Talentd
FleetCode
Make and follow sheets.Sign in

Count Elements With Maximum Frequency solution and explanation

EasyArrayCountingHash Table4 min read79.8% acceptanceUpdated 9 Apr 2026
Count Elements With Maximum Frequency | One Pass | Two Pass | Leetcode 3005codestorywithMIK · 12:50 · 7K viewsWatch on YouTube
9 more videos on this problem
  1. Count Elements With Maximum Frequency | One Pass | Two Pass | Leetcode 3005codestorywithMIK · 12:50 · 7K views
  2. Leetcode | 3005. Count Elements With Maximum Frequency | Easy | Java SolutionDeveloper Docs · 7:20 · 3K views
  3. 3005. Count Elements With Maximum Frequency (Leetcode Easy)Programming Live with Larry · 3:15 · 966 views
  4. 3005. Count Elements with Maximum Frequency (Python) | LeetcodeQuoc Dat Phung · 4:27 · 672 views
  5. 3005. Count Elements With Maximum Frequency | Leetcode Daily - PythonLeetcode Daily · 6:05 · 485 views
  6. LeetCode 3005: Count Elements With Maximum Frequency | Java Solution | HashMap ApproachCode Scribbler · 5:57 · 344 views
  7. Count Elements With Maximum Frequency | LeetCode 3005 | Java Code | Developer CoderDeveloper Coder · 6:38 · 190 views
  8. LeetCode 3005: Count Elements With Maximum Frequency | Python Solution | Hash Map CountingCode Scribbler · 5:40 · 136 views
  9. LeetCode 3005 Solution - Maximum Frequency ProblemScott Hacks Code · 6:25 · 119 views
  10. 3005. Count Elements With Maximum Frequency | Use of Hash Map | DCC | 08th March 2024 | LeetCodeCode Warehouse · 5:05 · 100 views

The problem

You are given an array nums consisting of positive integers.

Return the total frequencies of elements in nums such that those elements all have the maximum frequency.

The frequency of an element is the number of occurrences of that element in the array.

Example 1:

Input: nums = [1,2,2,3,1,4]
Output: 4
Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 5
Explanation: All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Approach overview

Problem Overview: You receive an integer array and need to determine which values appear most frequently. Instead of returning the value itself, return the total number of occurrences of all elements that share the maximum frequency.

Approach 1: Iterative Traversal with Stack (O(n) time, O(n) space)

This method processes the array iteratively while using a stack to manage traversal order. Each element is pushed onto the stack and processed once. A frequency map (hash table) tracks how many times each number appears. While popping elements from the stack, update the count in the map and keep track of the current maximum frequency. After the traversal completes, iterate through the map and sum the counts of elements whose frequency equals the maximum.

The key idea is that every element is visited exactly once, and hash lookups provide constant-time updates. This keeps the overall complexity linear. The stack mainly acts as a structured traversal helper while the hash map performs the counting. This pattern appears frequently in problems involving Array traversal combined with Hash Table aggregation.

Approach 2: Recursive Method (O(n) time, O(n) space)

The recursive approach processes the array index by index. Each recursive call handles one element, updates its frequency in a hash map, and passes the map to the next call. During recursion, maintain a variable storing the maximum frequency seen so far. After reaching the base case (end of the array), iterate through the frequency map and sum all counts equal to the maximum frequency.

This approach demonstrates how counting logic can be expressed without explicit loops. The recursion stack replaces iterative traversal while the map stores frequencies. Time complexity remains O(n) because each element is processed once, though the recursion adds O(n) auxiliary stack usage. The main concept is still frequency tracking, a common pattern in Counting problems.

Recommended for interviews: Interviewers generally expect a direct counting solution using a hash map and a single pass through the array. The iterative approach demonstrates solid understanding of frequency maps and linear traversal. A recursive version works but adds unnecessary overhead, so the iterative counting pattern is typically preferred for clarity and efficiency.

Approach 1: Approach 1: Iterative Traversal with Stack

This approach uses an iterative method to traverse the structure utilizing a stack for efficient element retrieval and management. This reduces the overhead associated with recursion, like function call stack management.

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> s;
    s.push(10);
    s.push(20);
    s.push(30);

    cout << s.top() << " popped from stack\n";
    s.pop();

    return 0;
}
#include <stdio.h>
#include <stdlib.h>

// A simple stack structure in C
struct Stack {
    int top;
    unsigned capacity;
    int* array;
};

// Function to create a stack
struct Stack* createStack(unsigned capacity) {
    struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
    stack->capacity = capacity;
    stack->top = -1;
    stack->array = (int*) malloc(stack->capacity * sizeof(int));
    return stack;
}

// Stack is full when top is equal to the last index
int isFull(struct Stack* stack) { return stack->top == stack->capacity - 1; }

// Stack is empty when top is -1
int isEmpty(struct Stack* stack) { return stack->top == -1; }

// Function to add an item to stack
void push(struct Stack* stack, int item) {
    if (isFull(stack))
        return;
    stack->array[++stack->top] = item;
}

// Function to remove an item from stack
int pop(struct Stack* stack) {
    if (isEmpty(stack))
        return -1;
    return stack->array[stack->top--];
}

int main() {
    struct Stack* stack = createStack(100);
    push(stack, 10);
    push(stack, 20);
    push(stack, 30);
    printf("%d popped from stack\n", pop(stack));
    return 0;
}

This C++ code uses the standard library stack to easily manage data push and pop operations with in-built functionality.

Complexity

Time Complexity: O(1) for both push and pop operations.
Space Complexity: O(n) for the stack space consumption.

Try this approach in the editor

Approach 2: Approach 2: Recursive Method

This approach utilizes a recursive method to process elements. It is intuitive and straightforward but needs careful consideration of recursive depth and stack limits in various environments.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)


number = 5
print("Factorial of", number, "is", factorial(number))
public class RecursiveDemo {
    public static int factorial(int n) {
        if (n == 0) return 1;
        else return(n * factorial(n - 1));
    }

    public static void main(String[] args) {
        int number = 5;
        System.out.println("Factorial of " + number + " is " + factorial(number));
    }
}

This Python program calculates the factorial of a number using recursion, showcasing the elegance of recursive functions in Python due to its succinct syntax.

Complexity

Time Complexity: O(n) with respect to the input number.
Space Complexity: O(n) due to recursion stack space.

Try this approach in the editor

Approach 3: Counting

We can use a hash table or array cnt to record the occurrence of each element.

Then we traverse cnt to find the element with the most occurrences, and let its occurrence be mx. We sum up the occurrences of elements that appear mx times, which is the answer.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the array nums.

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxFrequencyElements = function (nums) {
    const cnt = new Array(101).fill(0);
    for (const x of nums) {
        ++cnt[x];
    }
    let [ans, mx] = [0, -1];
    for (const x of cnt) {
        if (mx < x) {
            mx = x;
            ans = x;
        } else if (mx === x) {
            ans += x;
        }
    }
    return ans;
};
function maxFrequencyElements(nums: number[]): number {
    const cnt: number[] = Array(101).fill(0);
    for (const x of nums) {
        ++cnt[x];
    }
    let [ans, mx] = [0, -1];
    for (const x of cnt) {
        if (mx < x) {
            mx = x;
            ans = x;
        } else if (mx === x) {
            ans += x;
        }
    }
    return ans;
}
public class Solution {
    public int MaxFrequencyElements(int[] nums) {
        int[] cnt = new int[101];
        foreach (int x in nums) {
            ++cnt[x];
        }
        int ans = 0, mx = -1;
        foreach (int x in cnt) {
            if (mx < x) {
                mx = x;
                ans = x;
            } else if (mx == x) {
                ans += x;
            }
        }
        return ans;
    }
}
func maxFrequencyElements(nums []int) (ans int) {
	cnt := [101]int{}
	for _, x := range nums {
		cnt[x]++
	}
	mx := -1
	for _, x := range cnt {
		if mx < x {
			mx, ans = x, x
		} else if mx == x {
			ans += x
		}
	}
	return
}
impl Solution {
    pub fn max_frequency_elements(nums: Vec<i32>) -> i32 {
        let mut cnt = [0; 101];
        for &x in &nums {
            cnt[x as usize] += 1;
        }
        let mut ans = 0;
        let mut mx = -1;
        for &x in &cnt {
            if mx < x {
                mx = x;
                ans = x;
            } else if mx == x {
                ans += x;
            }
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Iterative Traversal with Stack

Time Complexity: O(1) for both push and pop operations.
Space Complexity: O(n) for the stack space consumption.

Approach 2: Recursive Method

Time Complexity: O(n) with respect to the input number.
Space Complexity: O(n) due to recursion stack space.

Counting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterative Traversal with StackO(n)O(n)General case when iterating through the array and building a frequency map using a hash table
Recursive MethodO(n)O(n)Useful for demonstrating recursion-based traversal or practicing recursion with counting logic

Frequently asked questions

Is Count Elements With Maximum Frequency easy or hard?

LeetCode classifies this problem as Easy. The main skill required is building and using a frequency map with a hash table, a common pattern in array and counting problems.

Count Elements With Maximum Frequency Python/Java solution

In Python, a dictionary or collections.Counter can track frequencies, while Java typically uses HashMap<Integer, Integer>. Both implementations iterate through the array, update counts, track the maximum frequency, and sum occurrences of elements with that maximum.

How to solve Count Elements With Maximum Frequency in O(n)?

Traverse the array and store frequencies in a hash map. Track the maximum frequency while updating counts. After processing all elements, sum the frequencies of values whose count equals the maximum frequency. This approach requires O(n) time and O(n) space.

What is the best approach for Count Elements With Maximum Frequency?

The most efficient approach uses a hash table to count the frequency of each element in one pass through the array. After building the frequency map, track the maximum frequency and sum the counts of all elements that match it. This runs in O(n) time and O(n) space.

Is Count Elements With Maximum Frequency asked at Google/Amazon/Meta?

Frequency counting problems are common in interviews at companies like Amazon, Google, and Meta because they test hash table usage and array traversal. Variations of this problem appear frequently in coding rounds and online assessments.

What data structure is used in Count Elements With Maximum Frequency?

A hash table (or dictionary/map) is the primary data structure used. It stores the frequency of each integer in the array and allows constant-time updates and lookups, making it ideal for counting-based problems.

What is the time complexity of Count Elements With Maximum Frequency?

The optimal solution runs in O(n) time because each element in the array is processed once while updating a frequency map. A second pass over the map to sum the maximum frequencies also takes linear time relative to unique elements, keeping the overall complexity O(n).

Comments

Now write it yourselfClose this page and solve Count Elements With Maximum Frequency in the editor, without looking.
Practise Count Elements With Maximum Frequency