Count Elements With Maximum Frequency - Problem

You're given an array nums of positive integers, and your task is to find elements that appear most frequently, then sum up their total occurrences.

Here's how it works: First, determine the maximum frequency (the highest number of times any element appears). Then, find all elements that appear exactly this many times, and return the sum of all their frequencies.

Example: If array [1,2,2,3,1,4] has elements 1 and 2 each appearing 2 times (maximum frequency), while others appear once, the answer is 2 + 2 = 4.

Input & Output

example_1.py โ€” Basic case with multiple max frequencies
$ Input: [1,2,2,3,1,4]
โ€บ Output: 4
๐Ÿ’ก Note: Elements 1 and 2 both appear 2 times (maximum frequency). Sum = 2 + 2 = 4
example_2.py โ€” Single element with max frequency
$ Input: [1,2,3,4,5]
โ€บ Output: 5
๐Ÿ’ก Note: All elements appear once (maximum frequency = 1). Sum = 1 + 1 + 1 + 1 + 1 = 5
example_3.py โ€” One dominant element
$ Input: [1,1,1,2,2,3]
โ€บ Output: 3
๐Ÿ’ก Note: Element 1 appears 3 times (maximum frequency). Only element 1 has max frequency. Sum = 3

Visualization

Tap to expand
Real-time Frequency Tracking๐ŸŽต Music Streaming Analytics DashboardProcessing playlist: [Song1, Song2, Song2, Song3, Song1, Song4]๐Ÿ“Š Current StatsMax Plays: 2Top Songs: 2Total: 4๐ŸŽค Song Play CountsSong1: 2Song2: 2Song3: 1Song4: 1๐Ÿ† Top ChartsMost Popular:๐ŸŽต Song1 (2 plays)๐ŸŽต Song2 (2 plays)Total Top Plays: 4๐ŸŽฏ Algorithm tracks popularity in real-time!Result = max_plays ร— num_top_songs = 2 ร— 2 = 4
Understanding the Visualization
1
Initialize Tracking
Start with empty frequency map, max_freq=0, count=0
2
Process Each Element
Update frequency and check if it becomes new maximum
3
Update Maximum Tracking
When frequency exceeds max, reset count; when equal, increment count
4
Calculate Result
Return max_freq ร— count (total frequencies of most frequent elements)
Key Takeaway
๐ŸŽฏ Key Insight: By tracking the maximum frequency and count of elements with that frequency simultaneously during our single pass, we eliminate the need for multiple passes through the data, achieving optimal O(n) time complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array with O(1) hash table operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash table stores at most n unique elements

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค nums[i] โ‰ค 100
  • All elements are positive integers
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
89.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen