878. Top-k indices for every row
Why it matters Top-k per row shows up in retrieval (top documents per query), MoE routing (top experts per token) and sampling (top-k tokens).
topk_per_row(scores, k) returns, for every row, the column indices of the k largest scores, largest first. Ties keep the lower column index first.
Inputs: scores is a list or ndarray of shape (n, m). k is an int with 1 <= k <= m.
Return an ndarray of ints with shape (n, k).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 30 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def topk_per_row(scores, k)Example 1
Input: topk_per_row([[0.1, 0.9, 0.5], [3.0, 1.0, 2.0]], 2)
Output: [[1, 2], [0, 2]]
Example 2
Input: scores = [[1.0, 1.0, 0.0]], k = 2
Output: [[0, 1]]
Example 3
Input: scores = [[4.0, 2.0]], k = 1
Output: [[0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Sort along axis=1.
Hint 2
Negate to get descending order, and use kind='stable' for ties.
Hint 3
Slice the first k columns.
Common mistakes
- Reversing an ascending sort, which flips tie order.
- argpartition without sorting the selected k.
- Returning values instead of indices.
Understand the idea
np.argsort works along any axis. Sorting the negated scores with a stable sort gives descending order with ties in column order, for every row at once. For very wide rows, np.argpartition picks the top k in O(m) per row and you only sort those k.
Shapes and data flow
scores: (n, m). Output: (n, k).