Code Room
CodingMediumcod-g1082
Subject Query top nLevel Mid–Senior~25 minCommon in Databases & SQL · Algorithms & data structures interviewsIndustries Software development, Technology

Question

Implement ORDER BY ... LIMIT N (top-N). Given rows (list of dicts), a sort_col, a direction ('asc' or 'desc'), and an integer n, return the first n rows after sorting by row[sort_col] in the given direction. The sort must be stable, so rows with equal sort keys keep their input order. If n is greater than the row count, return all rows; if n <= 0, return an empty list. Return the list of selected rows.

Implement
top_n(rows: list[dict], sort_col: str, direction: str, n: int) → list[dict]
Examples
in[[{"s":30,"id":1},{"s":10,"id":2},{"s":20,"id":3}],"s","desc",2]out[{"s":30,"id":1},{"s":20,"id":3}]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.