15% off all plans & roadmaps Use code
See plansLeetCode 347 · Solution & editorial
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Top K Frequent Elements is a Heap (Priority Queue) Patterns problem, in the Top K Elements (Selection/Frequency) subpattern. The pattern covers top K elements, K-way merge, two heaps for median, and scheduling
Find top K elements using heap. Solve kth largest, top K frequent, and k closest points problems.
The reference solution runs in O(n) time and O(n) space.
Top K Frequent Elements has been reported in interviews at Amazon, Apple, Bloomberg, ByteDance, Capital One, eBay, Facebook, Google.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Top K Frequent Elements is a Heap (Priority Queue) Patterns problem, in the Top K Elements (Selection/Frequency) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.