Problem 3005

Abstract / Summary

Count how many numbers occur as many times as the highest frequency among all numbers in the list.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 3005.py

class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        freq = defaultdict(int)
        for n in nums:
            freq[n] += 1

        val  = list(freq.values())
        high = max(val)
        return val.count(high) * high
9 lines | 263 bytes | submitted March 11, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that receives a list of integers and returns the total number of elements that belong to the most frequent value(s). It first builds a frequency map, then isolates the frequency counts, identifies the highest occurrence count, and finally computes how many elements appear with that highest frequency. The result is the product of the highest frequency and the number of distinct values that achieve it.

Key Steps

Frequency Counting

A defaultdict of integers is created to accumulate how many times each distinct number appears in the input list. The loop iterates over every element, incrementing the corresponding entry in the dictionary.

freq = defaultdict(int)
for n in nums:
    freq[n] += 1

Extracting Frequency Values

After the map is populated, only the frequency numbers are needed for further analysis. The values of the dictionary are collected into a plain list.

val = list(freq.values())

Determining Maximum Frequency

The highest occurrence count among all distinct numbers is obtained using the built-in max function applied to the list of frequencies.

high = max(val)

Computing Result

The method counts how many distinct numbers share this maximum frequency and multiplies that count by the frequency itself. This yields the total number of elements that belong to the most frequent group(s).

return val.count(high) * high

Edge Cases Handled

When the input list contains a single unique value repeated many times, the frequency map holds one entry, the maximum frequency equals the length of the list, and the count of that maximum is one, resulting in the original list length being returned.

If several different numbers appear the same maximal number of times, the count operation correctly identifies all of them, and the multiplication aggregates their contributions, delivering the combined total of those elements.

When all numbers are distinct, each frequency is one, the maximum frequency is one, and the count of that maximum equals the number of distinct elements, so the method returns the size of the original list, reflecting that every element belongs to a most-frequent group of size one.

The use of defaultdict ensures that any integer, including negative values or zero, can be processed without additional existence checks, allowing the algorithm to handle the full integer domain seamlessly.

Performance Optimizations

The algorithm leverages a single pass over the input list to build the frequency map, avoiding multiple traversals. The defaultdict provides constant-time updates for each element, eliminating the need for explicit key existence tests.

Subsequent operations-converting dictionary values to a list, finding the maximum, and counting occurrences of that maximum-are performed using Python’s built-in functions, which are implemented in C and thus execute with minimal overhead compared to equivalent pure-Python loops.

By separating the concerns of counting frequencies and evaluating the result, the code maintains a clear data flow that benefits from Python’s optimized collection handling, resulting in an efficient overall execution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bucket full of different colored blocks. This code is like a little robot helper that wants to find out which colors appear the most. First, the robot goes through the bucket and picks up every block one by one, keeping a tally in a notebook to remember how many of each color it found.

Once the notebook is full of all the counts, the robot looks at all those numbers to see what the biggest count is. If the highest number in the notebook is five, that means some colors showed up five times.

After finding that biggest count, the robot looks through the notebook again to see how many different colors reached that top score. If three different colors all showed up five times, the robot adds five plus five plus five to get the final answer. This tells you the total number of blocks that belong to those most popular color groups.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.22 | σ = 1.71

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java C++ JS Go C# Rust TS
Progiez Python Java C++
github charles-wangkai Java
fsq C++
JoshCrozier JS
muhammadfarhankt Go
pruthvikp Python
trung-hn Python
varunu28 Java
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
muhammadfarhankt Go
pruthvikp Python
trung-hn Python
varunu28 Java
withaarzoo C++
26 links | 12 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   March 11, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality