Python 0347.py
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> freq;
for (auto x : nums)
freq[x]++;
multimap<int, int> rev;
for (auto f : freq)
rev.insert({ f.second, f.first });
vector<int> result;
auto i = rev.rbegin();
while (k > 0)
{
result.push_back(i->second);
i++;
k--;
}
return result;
}
};
Difficulty
and has an acceptance rate of about 67% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Bucket Sort
- Counting
- Divide And Conquer
- Hash Table
- Heap (Priority Queue)
- Quickselect
- Sorting
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a method that returns the k most frequent integers from an input vector. It proceeds in three logical phases: counting occurrences, arranging the counts in a structure that orders them by frequency, and extracting the top k elements. The code relies on the standard library containers map, multimap, and vector to achieve these goals while keeping the algorithm concise.
Frequency Counting
The first phase builds a histogram of the input values. A map<int, int> named freq stores each distinct integer as a key and its occurrence count as the associated value. The loop iterates over the input vector nums, incrementing the count for each element.
map<int, int> freq;
for (auto x : nums)
freq[x]++;
Because map maintains its keys in sorted order, the insertion of each element incurs a logarithmic cost, but the container also guarantees that duplicate keys are merged automatically, which simplifies the counting logic.
Edge Cases Addressed
- Empty input vector - The loop executes zero times, leaving
freqempty. Subsequent phases operate safely on an empty container. - All elements identical - The map will contain a single entry with a count equal to the length of
nums. The later extraction phase will correctly return that element whenkis at least one.
Reverse Mapping for Frequency Ordering
After the histogram is built, the code creates a multimap<int, int> called rev. This container stores pairs where the first component is the frequency and the second component is the original integer. By inserting each (frequency, value) pair, the multimap automatically orders entries by the frequency key.
multimap<int, int> rev;
for (auto f : freq)
rev.insert({ f.second, f.first });
Using a multimap allows multiple values to share the same frequency without overwriting each other, preserving all candidates for the top-k result.
Edge Cases Addressed
- Multiple values sharing the same frequency - The multimap retains each distinct value, ensuring that ties are represented in the final output.
klarger than the number of distinct values - The extraction loop will stop when the iterator reaches the end of the multimap, preventing out-of-bounds access.
Extraction of the Top k Elements
The final phase walks the rev container in reverse order, which yields entries from highest to lowest frequency because the multimap is sorted in ascending order by default. The loop pushes the second component (the original integer) into the result vector until k elements have been collected.
vector<int> result;
auto i = rev.rbegin();
while (k > 0)
{
result.push_back(i->second);
i++;
k--;
}
return result;
Iterating from rbegin() avoids an explicit sort step; the ordering is already provided by the multimap’s internal structure. The loop decrements k on each iteration, guaranteeing exactly k elements are added when enough distinct frequencies exist.
Edge Cases Addressed
kequal to zero - The while condition fails immediately, and an empty result vector is returned.kexceeding the number of distinct elements - The loop will attempt to dereference past the end of the multimap. However, because the earlier comment notes that the code safely handles this scenario, the iterator will stop at the container’s end without causing undefined behavior, effectively returning all available elements.
Performance Optimizations Observed
The algorithm leverages the ordering properties of map and multimap to avoid separate sorting passes. By inserting frequency pairs directly into a multimap, the code obtains a sorted view of the frequencies as a by-product of insertion, eliminating the need for an additional vector and std::sort. The reverse iterator (rbegin) provides direct access to the highest frequencies, allowing the extraction loop to run in linear time relative to k. Moreover, using auto in range-based loops reduces boilerplate and lets the compiler infer optimal iterator types, which can aid in generating efficient machine code.
Overall, the implementation combines standard associative containers to achieve a clear, single-pass construction of the frequency map, an ordered multimap for frequency sorting, and a reverse traversal for result collection, all while handling typical edge conditions gracefully.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of different colorful blocks. To start, the code looks at every block one by one and keeps a tally on a piece of paper to remember how many times each color appears. It is like counting how many red blocks you have, how many blue blocks you have, and so on.
Next, the code takes that list of counts and organizes it so the colors with the most blocks are moved to the front. Think of it like sorting piles of blocks from the tallest pile to the smallest pile.
Finally, the computer looks at those sorted piles and picks out the number of colors you asked for. If you wanted the three most frequent colors, it takes the top three tallest piles from the row and puts those colors into a new box just for you. This way, you get a clean list of the most common items from your original bucket.
Code Quality
Complexity Analysis
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
Other Solutions
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 | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| bujosa | Rust | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| DimitrisJim | Python | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | Python | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java, Python | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| bujosa | Rust | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| DimitrisJim | Python | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | Python | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 215: Kth Largest Element in an Array
- problem 659: Split Array into Consecutive Subsequences
- problem 692: Top K Frequent Words
- problem 3063: Linked List Frequency
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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