BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges7 of 14 in topic

878. Top-k indices for every row

MediumOptimization challenges

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.

Functiondef 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).
Topics
Optimization challenges
Similar questions
  • Vectorise pairwise Euclidean distancesMedium
  • Group-by mean without a Python loopMedium
  • Fast 2D valid convolutionMedium
  • IoU matrix for two sets of boxesMedium
All Optimization challenges problems
Report
878 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
import numpy as np
​
def topk_per_row(scores, k):
s = np.asarray(scores, dtype=float)
out = np.zeros((s.shape[0], k), dtype=int)
for i in range(s.shape[0]):
order = sorted(range(s.shape[1]), key=lambda j: (-s[i, j], j))
out[i] = order[:k]
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS