Neural Mastery
← Practice
Top K Frequent Elementsmedium

Top K Frequent Elements

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Count element frequencies and retrieve the top k keys in O(n log k) or O(n) time via bucket sorting or heaps.

Related Skills

Task

Implement top_k_frequent(nums, k): return the k most frequent elements in nums. Order the returned list by frequency descending, breaking frequency ties by value ascending.

Function Signature

top_k_frequent(nums: list[int], k: int) -> list[int]

Examples

Example 1: Clear Frequency Hierarchy
Input: nums = [1, 1, 1, 2, 2, 3] k = 2
Output: [1, 2]
Example 2: Single Element Array
Input: nums = [1] k = 1
Output: [1]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • 1 <= len(nums) <= 10^5.
  • k is in the range [1, number of unique elements].
  • Must run better than O(n log n).
Python3Saved ✓
def top_k_frequent(nums: list[int], k: int) -> list[int]:
"""Return the k most frequent elements in nums.
Return elements sorted by frequency descending (and by value ascending on ties)."""
# Your implementation here
pass

Case 1: Clear Frequency Hierarchy
Input: nums = [1, 1, 1, 2, 2, 3] k = 2
Expected: [1, 2]
Case 2: Single Element Array
Input: nums = [1] k = 1
Expected: [1]