Code RoomOrder by limit N
MediumPrep Room Coding #248

Order by limit N

CodingDatabases & SQLAlgorithms & data structuresMid–Senior~25 min

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.

0:00 of about 25 min
InputExpectedGot
[[{"s":30,"id":1},{"s":10,"id":2},{"s":20,"id":3}],"s","desc",2][{"s":30,"id":1},{"s":20,"id":3}]not run yetsample