AlgoMaster Logo
AlgoMasterPage with a Compound Keyset Cursormedium

Page with a Compound Keyset Cursor

medium

Keyset pagination continues after the last row from the previous page instead of skipping an offset. A compound cursor is required when the primary sort column is not unique.

Design a KeysetPaginator class:

  • KeysetPaginator() creates a stateless paginator.
  • int[] nextPage(int[] timestamps, int[] ids, int cursorTimestamp, int cursorId, int limit) returns up to limit row IDs strictly after the cursor.

The aligned rows are already sorted by timestamp descending, then ID descending. A row (timestamp, id) is after the cursor when:

  • timestamp < cursorTimestamp, or
  • timestamp == cursorTimestamp and id < cursorId.

The special cursor (-1,-1) means before the first row and requests the first page. A non-sentinel cursor need not appear in the data.

Example 1:

Input:

Output:

Explanation: The next rows after (100,5) are (90,9) and (90,7).

Example 2:

Input:

Output:

Explanation: Even though (90,8) is absent, binary search begins at the first row ordered after it.

Constraints

  • 0 <= timestamps.length == ids.length <= 10^5
  • 0 <= timestamps[i], ids[i] <= 10^9
  • Rows are sorted by (timestamp DESC, id DESC) and IDs are unique.
  • The cursor is (-1,-1) or has non-negative components.
  • 0 <= limit <= 10^5
Hints

Loading...
CallReturns
new KeysetPaginator()null
nextPage([100,90,90,80], [5,9,7,2], 100, 5, 2)[9,7]

After cursor (100,5), the next two descending rows are (90,9) and (90,7).

Run checks these cases. Submit also runs a larger hidden set.