Asked at 12 companies
11 recent
- Meta
- Apple
- Walmart Labs
- Amazon
- Nvidia
- Snowflake
- Bloomberg
- Microsoft
- American Express
+2 moreShow fewer
- tcs
- Disney
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Builds on: Counting subarrays with a map of totals
Step 2
Try it on paper
5–10 minutes, no code yet
In the wild · Caches and duplicate detection: A hash map answers “have I seen this before?” in one step. It's how apps cache results, and how a photo app spots the same picture uploaded twice.
ProblemProblem statementGiven an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.ReadHide
Problem Statement
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Added 2026-11-05 from Srujan's LeetCode Recent AC list (photo) — not previously in the repo.
Input / Output
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Input: nums = [1], k = 1
Output: [1]
Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
Output: [1,2]
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Pattern Recognition
Bucket Sort — count frequencies with a hash map (Phase 1), then use the frequency itself as a bucket index. A number can appear at most n times, so there are only n buckets; the top k live in the fullest buckets. No sorting needed.
Approach
Brute Force — Count, Then Sort by Frequency, O(n log n)
freq = count each number
return the k keys with the largest counts, sorted by count
Optimized — Bucket Sort, O(n)
freq = count each number
buckets = [[] for _ in range(len(nums) + 1)]
for num, count in freq.items():
buckets[count].append(num) # frequency IS the index
walk buckets from fullest to emptiest, collect k numbers
Complexity
| Approach | Time | Space | Notes |
|---|---|---|---|
| Count + sort | O(n log n) | O(n) | Sorting the distinct keys |
| Bucket sort | O(n) | O(n) | Frequency as the bucket index |
(A size-k min-heap is the other standard answer at O(n log k) — same idea, keep only the k best.)
Solution code
from typing import List
from collections import Counter
class SolutionBruteForce:
"""O(n log n) time | O(n) space — count, then sort by frequency."""
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = Counter(nums)
ranked = sorted(freq.keys(), key=lambda x: freq[x], reverse=True)
return ranked[:k]
class Solution:
"""O(n) time | O(n) space — bucket sort by frequency."""
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for num, count in freq.items():
buckets[count].append(num) # frequency IS the index
result = []
for count in range(len(nums), 0, -1):
for num in buckets[count]:
result.append(num)
if len(result) == k:
return result
return resultOther ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language