Skip to content
mlmentorship

Use bounded occurrence counts as ranking coordinates

Place distinct values at their frequency coordinates, then change memory use or specify exact cutoff ties.

Published · 10 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Use bounded occurrence counts as ranking coordinates

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list nums and integer k with 0 <= k <= u, where u is its distinct-value count. Output. Return k distinct values with the highest occurrence counts. Rules. Rank by frequency, not by numeric value. Equal occurrences contribute to their value's count. Any selection among cutoff-tied values is valid, and no output ordering is required. Leave the input unchanged. Rank zero returns []; an empty list therefore permits only zero. Example. [1, 1, 1, 2, 2, 3] with k = 2 returns [1, 2] in either order. For [5, 5, 9] and k = 1, return [5], not [9].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Frequency is a bounded coordinate: place each value at its count, then scan counts from n down until k values are collected.

Problem trace

Frequency chooses the bucket; each distinct value enters that bucket once

Input and goalReturn the `k` values that appear most often.
Count the concrete inputValue 1 appears three times, value 2 twice, and value 3 once. Select two distinct values.
101112232435
k2mapLabelfrequency
frequency132231
key 1
3
key 2
2
key 3
1

Recognize it
Use frequency buckets when the answer ranks values by occurrence count, counts cannot exceed the input length n, and linear time matters more than ordering values within equal-frequency buckets.
Keep true
Before scanning bucket f, the answer contains every value from frequencies greater than f and no value from a lower frequency. Therefore the first k collected values are among the k most frequent.
Reuse it
Whenever a ranking key is a small bounded integer, use that key as an array coordinate and scan coordinates in answer order; this transfers to counting sort, histogram selection, and bounded-score ranking.
Value 1 appears three times, value 2 twice, and value 3 once. Select two distinct values. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does bucket three contain value one rather than three copies of that value?
Full interview answer 10 min read

Return the distinct input values that occur most frequently, rather than the largest numeric values.

Problem

Input. An integer list nums and integer k with 0 <= k <= u, where u is its distinct-value count.

Output. Return k distinct values with the highest occurrence counts.

Rules. Rank by frequency, not by numeric value. Equal occurrences contribute to their value’s count. Any selection among cutoff-tied values is valid, and no output ordering is required. Leave the input unchanged. Rank zero returns []; an empty list therefore permits only zero.

Example. [1, 1, 1, 2, 2, 3] with k = 2 returns [1, 2] in either order. For [5, 5, 9] and k = 1, return [5], not [9].

Picture

Imagine a row of coordinates labelled 0 through n. A value’s frequency tells you exactly where it belongs. No positive count exceeds the input length n.

ValueFrequencyBucket
133
222
311

Skip empty buckets 6,5,4, take value 1 from bucket 3, then value 2 from bucket 2.

Problem trace

Separate count buckets: frequency, not numeric value, determines order

Worked example: evict by frequency, not by the value itselfValues occupy buckets according to how often they appear, not how large their names are. Scan from the highest frequency and stop after two values have been retained. Renaming a value cannot move its frequency bucket.Scan descending frequencies, notdescending numeric valuesbucket 51bucket 48two collected: stopbucket 39Emit one and eight. Nine remains inan unvisited lower-frequency bucket.
Read it this way: Values occupy buckets according to how often they appear, not how large their names are. Scan from the highest frequency and stop after two values have been retained. Renaming a value cannot move its frequency bucket. If nine becomes ninety without changing its frequency, does it enter the retained top two?
Reference drawing

Problem trace

Frequency chooses the bucket; each distinct value enters that bucket once

Worked example: evict by frequency, not by the value itselfValues occupy buckets according to how often they appear, not how large their names are. Scan from the highest frequency and stop after two values have been retained. Renaming a value cannot move its frequency bucket.Scan descending frequencies, notdescending numeric valuesbucket 51bucket 48two collected: stopbucket 39Emit one and eight. Nine remains inan unvisited lower-frequency bucket.
Execution trace
Input and goalReturn the `k` values that appear most often.
Count the concrete inputValue 1 appears three times, value 2 twice, and value 3 once. Select two distinct values.
101112232435
k2mapLabelfrequency
frequency132231
key 1
3
key 2
2
key 3
1

Recognize it
Use frequency buckets when the answer ranks values by occurrence count, counts cannot exceed the input length n, and linear time matters more than ordering values within equal-frequency buckets.
Keep true
Before scanning bucket f, the answer contains every value from frequencies greater than f and no value from a lower frequency. Therefore the first k collected values are among the k most frequent.
Reuse it
Whenever a ranking key is a small bounded integer, use that key as an array coordinate and scan coordinates in answer order; this transfers to counting sort, histogram selection, and bounded-score ranking.
Value 1 appears three times, value 2 twice, and value 3 once. Select two distinct values. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does bucket three contain value one rather than three copies of that value?
Read it this way: Values occupy buckets according to how often they appear, not how large their names are. Scan from the highest frequency and stop after two values have been retained. Renaming a value cannot move its frequency bucket. If nine becomes ninety without changing its frequency, does it enter the retained top two?

Before scanning bucket f, all higher-frequency candidates have been collected; no lower-frequency candidate has been collected. That ordering makes the first k collected values a valid selection. A cutoff bucket can temporarily add more than k; slicing keeps exactly k.

Code

from collections import Counter

def top_k_frequent(nums: list[int], k: int) -> list[int]:
   frequencies = Counter(nums)
   buckets: list[list[int]] = [[] for _ in range(len(nums) + 1)]

   for num, frequency in frequencies.items():
      buckets[frequency].append(num)

   answer: list[int] = []
   for bucket in reversed(buckets):
      answer.extend(bucket)
      if len(answer) >= k:
         return answer[:k]
   return answer

Expected time and storage are , including counts, n+1 buckets, and collected values. Hashing supports the expected-time qualification. The input is unchanged.

Failure Check

Do not replace frequency priority with numeric rank. Within a bucket, this Python reference follows first appearance, not numeric order. For [2,1,3,3], k=2 returns [3,2]; [3,1] is also a valid tied selection. k=0 returns []. Larger k is outside the teaching contract; the literal source returns all candidates rather than raising.

Change the Coordinate Storage

New task: Avoid allocating n+1 buckets.

Picture and change: Keep exact counts, then select across the u distinct candidates with standard heap selection. Retain Counter from the reference above.

import heapq

def top_k_by_heap(nums, k):
   frequencies = Counter(nums)
   return heapq.nlargest(k, frequencies, key=frequencies.get)

Check: The source returns [1,2]; k=0 returns []. Expected work is , with state. The exact count map remains: this is not an -memory heavy-hitter estimator.

Use when: The bucket range is costly relative to the distinct candidates and requested selection.

Change the Tie Contract

New task: Equal frequencies must prefer the smaller numeric value.

Picture and change: Order distinct values by (-frequency, value). The extra key supplies an exact output order instead of an arbitrary cutoff choice.

def top_k_deterministic(nums, k):
   frequencies = Counter(nums)
   return sorted(frequencies, key=lambda value: (-frequencies[value], value))[:k]

Check: [2,1,3,3], k=2, now returns [3,1]. Expected counting plus comparison ranking costs time and storage. Do not keep the bucket method’s linear ranking claim for this version.

Use when: Exact numeric tie order is part of the result contract.

Transfer Check

Why not apply the same direct bucket scan to arbitrary real-valued scores?

Answer

The small integer coordinate range justified the array allocation and scan. Continuous or unbounded scores need another ordering structure, or an explicitly lossy quantization rule. Compare bounded value heaps when the weakest retained candidate should be exposed directly.