Interview conceptCoding & Algorithms

Cursor-Based Pagination

Asked of: Software Engineer

Last updated

What's being tested

These problems test cursor-based pagination: maintaining a deterministic position through ordered results without relying on fragile offset arithmetic. You must demonstrate cursor encoding, tie-breaker ordering, boundary handling, bidirectional state management, and efficient filtering or iteration.

Patterns & templates

  • Use a stable sort (primary_key, unique_id) so equal timestamps or scores never produce duplicates or skipped records.

  • Encode the last item’s sort keys into an opaque cursor; validate, decode, and reject malformed or incompatible cursors.

  • Forward query: fetch limit + 1, return the first limit, and set hasNextPage from the extra record.

  • Backward query: reverse comparison and ordering, fetch limit + 1, then reverse the returned page before responding.

  • Prefer keyset predicates such as created_at < cursor_time OR (created_at = cursor_time AND id < cursor_id) over OFFSET.

  • Keep iterator state explicit: current index, direction, exhausted flag, and page boundaries; define behavior for empty input and limit <= 0.

  • Target O(log n + k) indexed retrieval for k results; filtering an unsorted array generally costs O(n) per page.

Common pitfalls

Pitfall: Sorting only by a non-unique field allows ties to move between pages, causing duplicates or omissions.

Pitfall: Returning exactly limit records cannot reliably determine whether another page exists; fetch one extra item.

Pitfall: Treating a cursor as a raw array index breaks when records are inserted or deleted between requests.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Featured in interview prep guides

Practice questions

Related concepts