Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Hash Map / Set High frequency Solution Available Practice Mode

Top K Frequent Elements LeetCode Solution

Tags: #Array #Hash Map #Heap #Bucket Sort

Approach Summary

Count frequencies with a map. Use a min-heap of size k or bucket sort by frequency for O(n) solution.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Hash Map / Set Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.

Framework: Hash Map / Set • Interview Prep: Tested at FAANG • Explore all Hash Map / Set problems & invariants →

How to Recognize This Pattern

  • Find k most frequent elements

Complexity Analysis

Time Complexity

O(n log k)

Space Complexity

O(n)

Tags

Array Hash Map Heap Bucket Sort

Frequently Asked Questions

What is the optimal time and space complexity for Top K Frequent Elements?
The optimal solution for Top K Frequent Elements achieves O(n log k) runtime complexity and requires O(n) auxiliary space. Time Complexity is O(N) using the Bucket Sort approach or O(N log k) using the Min-Heap approach, where N is the number of elements in nums and k is the number of top elements requested. Since k <= N, both are substantially faster than sorting all distinct elements O(N log N). Space Complexity is O(N) to store element counts in the hash map and the heap or bucket structure.
How do I identify that Top K Frequent Elements requires the Hash Map / Set pattern?
In technical interviews, look for key problem signals: Find k most frequent elements. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Hash Map / Set strategy.
What critical edge cases must be handled in Top K Frequent Elements?
Essential edge cases to verify include: k equals the number of unique elements (e.g. nums = [1, 2, 3], k = 3) — returns all distinct elements; Array contains negative numbers (e.g. [-1, -1, 2]) — hash map handles signed integers without special handling; All elements identical (e.g. [1, 1, 1, 1], k = 1) — returns [1]; k = 1 — immediately returns the single mode of the array. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Top K Frequent Elements?
Top K Frequent Elements is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Google.
Buy me a coffee
Daily Practice
0/0