0
0
Rest APIprogramming~5 mins

Pagination with limit and offset in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Pagination with limit and offset
O(offset + limit)
Understanding Time Complexity

When using pagination with limit and offset in APIs, it's important to understand how the time to get results changes as you ask for different pages.

We want to know how the number of operations grows when we move through pages.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

GET /items?limit=10&offset=30

// The server fetches 10 items starting from the 31st item in the list.
// It skips the first 30 items and returns the next 10.

This code fetches a page of items by skipping a number of items (offset) and returning a limited number (limit).

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Skipping items up to the offset before collecting the limited items.
  • How many times: The server processes each item up to the offset plus the limit, so roughly offset + limit times.
How Execution Grows With Input

As the offset grows, the server must skip more items before returning the page.

Input Size (offset)Approx. Operations
10About 20 (10 skipped + 10 returned)
100About 110 (100 skipped + 10 returned)
1000About 1010 (1000 skipped + 10 returned)

Pattern observation: The work grows linearly with the offset because more items are skipped before fetching the page.

Final Time Complexity

Time Complexity: O(offset + limit)

This means the time to get a page grows roughly with how far you skip plus how many items you want to return.

Common Mistake

[X] Wrong: "Fetching page 100 is just as fast as page 1 because the limit is the same."

[OK] Correct: Because the server still has to skip all items before the offset, so higher page numbers take more time.

Interview Connect

Understanding how pagination affects performance helps you design APIs that stay fast even with many pages. This skill shows you think about real user experience and server work.

Self-Check

"What if we changed offset to use a cursor instead? How would the time complexity change?"