Newest-First Transaction Pager with Offset and Cursor Modes
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Build a pager over transaction records that sorts newest-first with a deterministic tie-break and supports offset and keyset-cursor navigation with correct metadata.
You are building the read side of a transaction history endpoint. You get an unordered list of transaction records and must return one page of them, newest first. The caller picks one of two paging styles.
Each record is a dictionary with the keys id (unique, comparable with the other ids), userId, amount and createdAt (a numeric timestamp).
Function
Implement a function taking these parameters, in this order:
records: the list of transaction dictionaries, in arbitrary order.mode: either"offset"or"cursor".page_size: the maximum number of records to return on the page.position: where the page starts. Its meaning depends onmode.
It returns a dictionary.
Ordering
Records are ordered by the pair (createdAt, id) in descending order. The record with the largest createdAt comes first. Records with equal createdAt are ordered by larger id first. Because ids are unique, this is a strict total order, and every record has exactly one position.
Offset mode (mode == "offset")
positionis a non-negative integer offset into the ordered list, orNone, which means offset0.datais the ordered records from indexoffsetup to (not including)offset + page_size. Fewer records are returned if the list runs out. If the offset is at or beyond the end,datais empty.- Return a dictionary with exactly these keys:
"data": the page, as a list of the original record dictionaries."hasNext":Trueif at least one record exists after the last record of this page, that is,offset + len(data) < total. OtherwiseFalse."nextCursor": alwaysNonein this mode."total": the number of records inrecords.
Cursor mode (mode == "cursor")
positionis eitherNone(start from the newest record) or a two-element list[createdAt, id]. This is the sort key of the last record the caller has already seen.- The eligible records are those whose key
(createdAt, id)is strictly smaller than the cursor pair under ordinary tuple comparison, kept in the ordering above. IfpositionisNone, all records are eligible. The cursor does not need to match any existing record. datais the firstpage_sizeeligible records.- Return a dictionary with exactly these keys (there is no
"total"key in this mode):"data": the page."hasNext":Trueif some eligible records did not fit on the page, otherwiseFalse."nextCursor": ifhasNextisTrueand the page is non-empty, the list[createdAt, id]of the last record on the page. In every other case it isNone.
Constraints
0 <= len(records) <= 10^5page_size >= 0. Withpage_size == 0the page is empty. In cursor modehasNextis stillTrueif any record is eligible, andnextCursorisNonebecause the page has no last record.idvalues are unique withinrecordsand mutually comparable (all integers or all strings, matching the cursor's id type).createdAtvalues are comparable numbers and may repeat.- In offset mode,
positionisNoneor an integer>= 0. - In cursor mode,
positionisNoneor a list[createdAt, id]. - Do not modify the input records. Return the original record dictionaries unchanged.
Examples
Example 1
Input: fetch_transaction_page([{'id': 1, 'userId': 10, 'amount': 12.5, 'createdAt': 1000}, {'id': 2, 'userId': 11, 'amount': 8, 'createdAt': 1002}, {'id': 3, 'userId': 10, 'amount': 20, 'createdAt': 1002}, {'id': 4, 'userId': 12, 'amount': 5, 'createdAt': 999}], 'offset', 2, 0)
Output: {'data': [{'id': 3, 'userId': 10, 'amount': 20, 'createdAt': 1002}, {'id': 2, 'userId': 11, 'amount': 8, 'createdAt': 1002}], 'hasNext': True, 'nextCursor': None, 'total': 4}
Example 2
Input: fetch_transaction_page([{'id': 1, 'userId': 10, 'amount': 12.5, 'createdAt': 1000}, {'id': 2, 'userId': 11, 'amount': 8, 'createdAt': 1002}, {'id': 3, 'userId': 10, 'amount': 20, 'createdAt': 1002}, {'id': 4, 'userId': 12, 'amount': 5, 'createdAt': 999}], 'cursor', 2, None)
Output: {'data': [{'id': 3, 'userId': 10, 'amount': 20, 'createdAt': 1002}, {'id': 2, 'userId': 11, 'amount': 8, 'createdAt': 1002}], 'hasNext': True, 'nextCursor': [1002, 2]}
Example 3
Input: fetch_transaction_page([{'id': 1, 'userId': 10, 'amount': 12.5, 'createdAt': 1000}, {'id': 2, 'userId': 11, 'amount': 8, 'createdAt': 1002}, {'id': 3, 'userId': 10, 'amount': 20, 'createdAt': 1002}, {'id': 4, 'userId': 12, 'amount': 5, 'createdAt': 999}], 'cursor', 2, [1002, 2])
Output: {'data': [{'id': 1, 'userId': 10, 'amount': 12.5, 'createdAt': 1000}, {'id': 4, 'userId': 12, 'amount': 5, 'createdAt': 999}], 'hasNext': False, 'nextCursor': None}
Hints
Hint 1
Sorting by timestamp alone leaves ties undefined. Sort by the pair (createdAt, id), both descending, so each record has one fixed position.
Hint 2
Offset mode is a slice of the sorted list. hasNext is just whether the index right after the slice is still inside the list.
Hint 3
In cursor mode, keep records whose (createdAt, id) tuple is strictly less than the cursor tuple. Compare keys, do not look the cursor record up. Compare the eligible count with the page length to decide hasNext, and only emit a nextCursor when hasNext is true and the page is not empty.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
-
Build a strict total order. Sort the records by
(createdAt, id)in descending order. Timestamps can repeat, but ids are unique, so no two records ever compare equal. Every record gets exactly one position, and repeated calls always see the same order. -
Offset mode. Take the slice
ordered[start : start + page_size], wherestartis0whenpositionisNone.totalis the length of the whole ordered list.hasNextisstart + len(page) < total, meaning at least one record sits after the page.nextCursoris alwaysNone, since the caller tracks the next offset itself.
-
Cursor mode. The cursor is the key of the last record the caller saw.
- Keep the records whose key is strictly smaller than the cursor (all of them when the cursor is
None). Python's tuple comparison is lexicographic, so this means "older timestamp, or the same timestamp with a smaller id". That is exactly "comes later in the descending order". - Take the first
page_sizeof those eligible records. hasNextis true when the page is shorter than the eligible list.- When
hasNextis true and the page is non-empty,nextCursoris the key of the page's last record. Otherwise it isNone, so a caller is never handed a cursor that leads to an empty page. - No
totalis returned in this mode.
- Keep the records whose key is strictly smaller than the cursor (all of them when the cursor is
Why it is correct
- Since the order is total, the ties on
createdAtare resolved the same way every time, and a page boundary may fall inside a group of equal timestamps without losing or repeating a record. - In cursor mode the next page contains exactly the records strictly after the cursor key, so the cursor record is excluded and everything after it is included. Chaining pages therefore covers every record exactly once.
- The cursor is compared by key, not looked up, so it also works if the record it came from has since been removed, and an out-of-range cursor simply yields an empty page.
hasNextis derived from counts of records that really remain, so it is exact in both modes.
Complexity
Let n be the number of records and k the page size.
- Time:
O(n log n)per call, dominated by the sort. The cursor filter and the slice areO(n)andO(k). - Space:
O(n)for the sorted copy and the eligible list.
A production system would keep the data sorted once, find the cursor position by binary search, and return the next k items in O(log n + k). A database does the same with an index on (createdAt DESC, id DESC) and a LIMIT k + 1 query, where the extra row answers hasNext without counting.
Reference solution
from typing import Dict, List
def fetch_transaction_page(records: List[Dict], mode: str, page_size: int, position: object) -> Dict:
# Strict total order: newest first, with id breaking timestamp ties.
ordered = sorted(records, key=lambda r: (r["createdAt"], r["id"]), reverse=True)
if mode == "offset":
start = 0 if position is None else position
total = len(ordered)
page = ordered[start:start + page_size]
has_next = start + len(page) < total
return {
"data": page,
"hasNext": has_next,
"nextCursor": None,
"total": total,
}
# Cursor (keyset) mode.
if position is None:
eligible = ordered
else:
boundary = (position[0], position[1])
eligible = [
r for r in ordered
if (r["createdAt"], r["id"]) < boundary
]
page = eligible[:page_size]
has_next = len(page) < len(eligible)
next_cursor = None
if has_next and page:
tail = page[-1]
next_cursor = [tail["createdAt"], tail["id"]]
return {
"data": page,
"hasNext": has_next,
"nextCursor": next_cursor,
}