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 start
- 0
- guard
- 1 <= k=2 <= len(scores)=4
- index 0
- 0.1
- candidate index 1
- not shown→1
- candidate index 3
- not shown→3
- input start
- 0→not shown
- selected index 1
- 1→0
- selected index 3
- 3→1
- subset size
- not shown→k=2
- arithmetic
- not shown→argsort=[1,0]; reverse=[0,1]
- subset size
- k=2→not shown
- index 0
- index 1: 0.9→position 0 -> index 1 -> 0.9
- verification
- not shown→scores[1]=0.9 >= scores[3]=0.8
- result
- not shown→[1,3]
- arithmetic
- argsort=[1,0]; reverse=[0,1]→not shown
- 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.
Reference drawing
Problem trace
Map candidate-local sort positions back to original score indices
Execution trace
- input start
- 0
- guard
- 1 <= k=2 <= len(scores)=4
- index 0
- 0.1
- candidate index 1
- not shown→1
- candidate index 3
- not shown→3
- input start
- 0→not shown
- selected index 1
- 1→0
- selected index 3
- 3→1
- subset size
- not shown→k=2
- arithmetic
- not shown→argsort=[1,0]; reverse=[0,1]
- subset size
- k=2→not shown
- index 0
- index 1: 0.9→position 0 -> index 1 -> 0.9
- verification
- not shown→scores[1]=0.9 >= scores[3]=0.8
- result
- not shown→[1,3]
- arithmetic
- argsort=[1,0]; reverse=[0,1]→not shown
- 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.
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.