NeetCode 150 / Arrays & Hashing
MediumArrays & HashingO(n)

Dry run

nums = [1, 1, 1, 2, 2, 3], k = 2Step 1 of 9
1
0
1
1
1
2
2
3
2
4
3
5
counts
empty

Count how often each value appears. Start with an empty count.

Pythontime O(n log n) · space O(n)
1def topKFrequent(nums, k):
2 freq = {}
3 for num in nums:
4 freq[num] = freq.get(num, 0) + 1
5 items = sorted(freq.items(), key=lambda x: -x[1])
6 return [v for v, _ in items[:k]]
Variables
i—
value—
count—

Problem

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Examples

Input: nums = [1,1,1,2,2,3], k = 2Output: [1,2]

1 appears 3 times, 2 appears 2 times

Input: nums = [1], k = 1Output: [1]

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • k is in the range [1, number of unique elements]

Intuition

The answer only depends on how often each value shows up, not on position. Count every value once with a hash map, then the k most frequent values are just the top k entries of that count — sort the (at most n) distinct values by count and take the first k.

Brute force → Optimal

Brute force

For each distinct value, scan the whole array again to count how many times it appears, then sort.

Time O(n²)Space O(n)
Optimal

One pass to build a value → count map (O(n)), then sort the distinct entries by count and take the first k.

Time O(n log n)Space O(n)

Complexity

Time O(n log n)Space O(n)

Edge cases

  • k equals the number of distinct values: every distinct value is returned.
  • All values identical: one distinct value, always the answer when k = 1.

Common mistakes

  • Sorting the original array instead of the (value, count) pairs, which loses the frequency information.
  • Assuming the output order matters — the problem accepts any order, so don't over-engineer tie-breaking.

জটিলতা

O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(n)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Group Anagramsপরের সমস্যাEncode and Decode Strings →