Skip to content
mlmentorship

Top-K Scores

Return indices of the `k` largest scores in descending score order.

Published · 9 min read ·Role-specific ·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

Top-K Scores

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

Problem

Input. A one-dimensional NumPy array scores of finite values and an integer k with 1 <= k <= len(scores). Output. Return an array of k distinct original indices, in nonincreasing order of their corresponding scores. Rules. Return input positions, not scores or positions within a selected subset. At a tied cutoff, any highest-scoring membership is valid; equal-score indices need no particular order. Preserve the input. Empty input and out-of-range k raise ValueError in the reference. Example. Scores [0.1, 0.9, 0.4, 0.8] with k = 2 return [1, 3]. Those original positions contain 0.9 and 0.8, respectively.

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

Use partial partition only to select top-k membership, then sort those candidate indices by their scores for the required descending order.

Problem trace

Map candidate-local sort positions back to original score indices

Worked example: partition selects membership; it does not sort the selected candidatesCandidate indices (3,1) have correct membership but no score order. Sorting that subset returns indices (1,3).Correct membership still needs aseparate ordering stepOne permitted partition result; notscore sorted3score 0.81score 0.9Sort only these selected candidatesby score1score 0.93score 0.8Indices remain one and three; onlytheir output order changes.
Read it this way: Candidate indices (3,1) have correct membership but no score order. Sorting that subset returns indices (1,3). Does selecting the right two indices guarantee that the first returned score is the larger one?
Full interview answer 9 min read
Reading depth

Return the original positions of the highest scores, ordered from highest selected score to lowest.

Problem

Input. A one-dimensional NumPy array scores of finite values and an integer k with 1 <= k <= len(scores).

Output. Return an array of k distinct original indices, in nonincreasing order of their corresponding scores.

Rules. Return input positions, not scores or positions within a selected subset. At a tied cutoff, any highest-scoring membership is valid; equal-score indices need no particular order. Preserve the input. Empty input and out-of-range k raise ValueError in the reference.

Example. Scores [0.1, 0.9, 0.4, 0.8] with k = 2 return [1, 3]. Those original positions contain 0.9 and 0.8, respectively.

Picture

Partition selects membership {1, 3} without promising order. Sort only their gathered scores, then map those local positions through candidates. The trace uses one allowed candidate arrangement; NumPy may return another.

Problem trace

Map candidate-local sort positions back to original score indices

Input and goalReturn indices of the `k` largest scores in descending score order.
Validate k against score countFor four scores, k=2 passes validation.
input start0.100.910.420.83
guard1 <= k=2 <= len(scores)=4
input start
0
guard
1 <= k=2 <= len(scores)=4
index 0
0.1

Recognize it
Use argpartition when k ranked elements are needed from a much larger score vector and fully sorting all n scores is unnecessary.
Keep true
After partition, every selected candidate belongs to the top-k score group although candidate order is unspecified; after subset argsort reversal, those same indices are descending by score.
Reuse it
Separate selection from ordering: first isolate the small set that can contain the answer, then pay sorting cost only on that set.
For four scores, k=2 passes validation. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the selected scores' argsort positions index the candidate array before returning original score indices?
Reference drawing

Problem trace

Map candidate-local sort positions back to original score indices

Worked example: partition selects membership; it does not sort the selected candidatesCandidate indices (3,1) have correct membership but no score order. Sorting that subset returns indices (1,3).Correct membership still needs aseparate ordering stepOne permitted partition result; notscore sorted3score 0.81score 0.9Sort only these selected candidatesby score1score 0.93score 0.8Indices remain one and three; onlytheir output order changes.
Execution trace
Input and goalReturn indices of the `k` largest scores in descending score order.
Validate k against score countFor four scores, k=2 passes validation.
input start0.100.910.420.83
guard1 <= k=2 <= len(scores)=4
input start
0
guard
1 <= k=2 <= len(scores)=4
index 0
0.1

Recognize it
Use argpartition when k ranked elements are needed from a much larger score vector and fully sorting all n scores is unnecessary.
Keep true
After partition, every selected candidate belongs to the top-k score group although candidate order is unspecified; after subset argsort reversal, those same indices are descending by score.
Reuse it
Separate selection from ordering: first isolate the small set that can contain the answer, then pay sorting cost only on that set.
For four scores, k=2 passes validation. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the selected scores' argsort positions index the candidate array before returning original score indices?
Read it this way: Candidate indices (3,1) have correct membership but no score order. Sorting that subset returns indices (1,3). Does selecting the right two indices guarantee that the first returned score is the larger one?

Every selected score is at least every excluded score; equal-score membership is unspecified. Subset sorting adds descending order without changing membership.

Code

import numpy as np

def top_k_indices(scores: np.ndarray, k: int) -> np.ndarray:
   if not 1 <= k <= len(scores):
      raise ValueError("k must name an item in scores")
   candidates = np.argpartition(scores, -k)[-k:]
   return candidates[np.argsort(scores[candidates])[::-1]]

Selection plus subset sorting uses work. Peak index storage is : argpartition returns all indices, although the output contains only .

Change ties or input access

1. Choose earlier indices at the boundary

New task: break all equal-score ties by smaller original index; allow k=0.

Picture and change: select scores above the threshold, then fill from equal-score indices in input order.

def top_k_stable_indices(scores, count):
   scores = np.asarray(scores, dtype=float)
   if scores.ndim != 1 or not np.isfinite(scores).all():
      raise ValueError("expected finite score vector")
   if not 0 <= count <= len(scores):
      raise ValueError("invalid count")
   if count == 0:
      return np.empty(0, dtype=int)
   threshold = np.partition(scores, len(scores) - count)[len(scores) - count]
   above = np.flatnonzero(scores > threshold)
   equal = np.flatnonzero(scores == threshold)[:count - len(above)]
   selected = np.concatenate((above, equal))
   return selected[np.lexsort((selected, -scores[selected]))]

Check: [5, 5, 5], count 2, returns [0, 1].

Use when: reproducible boundary membership matters.

2. Read a stream once

New task: retain only candidates from finite scores.

Picture and change: keep a min-heap of (score, -index); its root is the worst retained candidate.

import heapq
import math

def streaming_top_k_indices(values, count):
   if count < 0:
      raise ValueError("negative count")
   if count == 0:
      return []
   heap = []
   for index, score in enumerate(values):
      if not math.isfinite(score):
         raise ValueError("expected finite score")
      candidate = score, -index
      if len(heap) < count:
         heapq.heappush(heap, candidate)
      elif candidate > heap[0]:
         heapq.heapreplace(heap, candidate)
   if len(heap) != count:
      raise ValueError("too few scores")
   return [-negative_index for score, negative_index in sorted(heap, reverse=True)]

Check: the fixture returns [1, 3]; three equal scores retain indices [0, 1].

Use when: bounded retained state outweighs partition’s vectorized selection.

Transfer: why stable sorting alone fails

Would stably sorting an arbitrary tied candidate subset guarantee earlier boundary indices?

Check your answer

No. An earlier tied index might already be excluded. Choose boundary membership before ordering; sorting cannot restore a missing item.

Index and score contracts

Returning local argsort positions answers a different question from returning original score indices. Always apply the local permutation through candidates.

The reference does not specify equal-score membership or order. Both adaptations choose descending score, then ascending original index. Their counts must be integers. The stable array variant converts scores to float64; inputs must retain their intended order and equality under that conversion. Do not silently use NaN ordering as a ranking policy.

Stable threshold selection still uses temporary arrays. The stream uses retained storage and work. Its zero-count case returns immediately without consuming the iterable. For positive counts, insufficient scores raise an error.

Neither asymptotic analysis nor this trace proves partition faster for every size, dtype or platform.