Resume a Sorted Score Listing from a Last-Seen Key
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Filter records by a minimum score, order them by score then id, and return one page after a (score, id) cursor along with the cursor for the following page.
You are given a collection of records, where each record is a dictionary with three keys:
id: a string, unique across the collectionscore: an integerpayload: a string
Write a function that returns one page of results from this collection, using a key-based cursor rather than a numeric offset.
Task
- Keep only records whose
scoreis greater than or equal tomin_score. - Order the kept records by
scoreascending. Records with equal scores are ordered byidascending (plain string comparison). - If
cursoris notNone, it is a two-element list[score, id]describing the last record the caller has already seen. Discard every record whose(score, id)pair is less than or equal to the cursor pair, so only records strictly after it remain. The cursor pair does not need to match an existing record. - Take the first
page_sizerecords of what remains. These form the page. - Compute the next cursor:
- If there are more records beyond the page, it is
[score, id]of the last record in the page. - Otherwise it is
None. In particular, if the remaining records fit exactly in the page, the next cursor isNone.
- If there are more records beyond the page, it is
Return value
Return a two-element list [page, next_cursor], where page is the list of record dictionaries (unchanged, with all three keys) in the order described above, and next_cursor is either [score, id] or None.
If nothing qualifies, return [[], None].
Constraints
- Up to 1,000,000 records.
1 <= page_size <= 1000.idvalues are unique;scorevalues are integers and may be negative or repeated.- The input list is in arbitrary order and does not change during a paginated scan.
- Cursor comparison uses the pair
(score, id): compare scores numerically first, then ids as strings.
Examples
Example 1
Input: fetch_page_after_key([{'id': 'b', 'score': 2, 'payload': 'B'}, {'id': 'a', 'score': 1, 'payload': 'A'}, {'id': 'c', 'score': 2, 'payload': 'C'}], 1, 2, None)
Output: [[{'id': 'a', 'score': 1, 'payload': 'A'}, {'id': 'b', 'score': 2, 'payload': 'B'}], [2, 'b']]
Example 2
Input: fetch_page_after_key([{'id': 'z', 'score': 4, 'payload': 'Z'}, {'id': 'a', 'score': 4, 'payload': 'A'}, {'id': 'm', 'score': 3, 'payload': 'M'}], 4, 1, [4, 'a'])
Output: [[{'id': 'z', 'score': 4, 'payload': 'Z'}], None]
Example 3
Input: fetch_page_after_key([{'id': 'x', 'score': 1, 'payload': 'X'}], 2, 5, None)
Output: [[], None]
Hints
Hint 1
Because ids are unique, the pair (score, id) gives every record a distinct position in a strict total order, so a cursor is just a position in that order.
Hint 2
You do not need to sort everything. Filter by min_score and by 'strictly greater than the cursor pair', then pick only the smallest few items.
Hint 3
Select page_size + 1 candidates: if the extra one exists, there is more data and the next cursor is the last item of the page; otherwise the next cursor is None.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since id is unique, the pair (score, id) is a distinct key for every record, and Python's tuple comparison orders by score first and then by id, which is exactly the required order. A cursor is therefore just a key, and "after the cursor" means "key strictly greater than the cursor key".
Steps:
- Turn the cursor into a tuple (or leave it as
None). - Lazily filter the records: keep those with
score >= min_scoreand, when a cursor exists,(score, id) > cursor_key. - Use
heapq.nsmallestwith key(score, id)to get the firstpage_size + 1eligible records in order. The extra record is only a probe for "is there more data?". - If more than
page_sizecandidates came back, there are further records, so the next cursor is the[score, id]of the last record on the page. Otherwise it isNone. - Return
[page, next_cursor].
Why it is correct
- The filter removes exactly the records below
min_scoreand those at or before the cursor key, so what remains is precisely the set that should follow. nsmallestreturns the smallest keys in ascending order, so the firstpage_sizeare the correct page.- Fetching one extra item tells us whether anything lies beyond the page. This avoids returning a cursor that leads to an empty page when the remaining count is an exact multiple of
page_size. - The cursor does not have to refer to an existing record, since the comparison is on key values only.
- Empty input or no qualifying records yields an empty page and
None.
Complexity
- Time: O(n log k) where n is the number of records and k =
page_size + 1(at most 1001), since each eligible record is considered once against a heap of size k. - Space: O(k) for the heap of candidates.
Reference solution
import heapq
from typing import Dict, List, Optional
def fetch_page_after_key(records: List[Dict[str, object]], min_score: int, page_size: int, cursor: Optional[List[object]]) -> List[object]:
cursor_key = tuple(cursor) if cursor is not None else None
eligible = (
rec for rec in records
if rec["score"] >= min_score
and (cursor_key is None or (rec["score"], rec["id"]) > cursor_key)
)
candidates = heapq.nsmallest(
page_size + 1,
eligible,
key=lambda rec: (rec["score"], rec["id"]),
)
has_more = len(candidates) > page_size
page = candidates[:page_size]
next_cursor = [page[-1]["score"], page[-1]["id"]] if has_more and page else None
return [page, next_cursor]