CODING CHALLENGE · N°63

API Pagination Collector

Easy FDEIntegrationsAPIs

The customer’s API returns 100 rows at a time behind a cursor. You need all of them. Follow the "next" pointer page by page until it runs out — the loop behind every "sync everything" integration. Solve it in Python or TypeScript, with hidden tests.

The problem

Implement collect(pages). pages models a cursor-paginated API as a list where each entry is {"items": [...], "next": index-or-None}. Start at index 0, append its items, follow next to the next page, and repeat until next is None. Return the flat list of all items in page order. (Guard against a cycle: never visit the same page twice.)

EXAMPLE 1
Input pages = [{"items":[1,2],"next":1},{"items":[3],"next":2},{"items":[4,5],"next":null}]
Output [1, 2, 3, 4, 5]
follow next: page 0 → 1 → 2, then stop
CONSTRAINTS
  • Begin at index 0 and follow next until it is None/null.
  • Concatenate each page’s items in the order visited.
  • Stop if you revisit a page (a malformed API could loop) — do not spin forever.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement collect(pages): walk from index 0 following next, extending an output list with each page’s items, tracking visited indices to break any cycle.

HINTS — 3 IDEAS
  1. Keep a current index (start 0) and a seen set of visited indices.
  2. While the index is not None and not already seen: mark it seen, extend the output with pages[i]["items"], set i to pages[i]["next"].
  3. Return the accumulated items.
CPython · WebAssembly
Approach, complexity & discussion — open after you solve

The approach

Follow the cursor page by page: call the endpoint, collect the page’s items, read the next token from the response, and repeat with that token until it comes back null or absent. Accumulate items across every page into one list.

Complexity

Time O(total items); network cost is O(number of pages) round-trips.

Common mistakes

  • An infinite loop if the next token never clears — guard with a max-pages cap or a seen-cursor check.
  • Dropping the final page’s items by stopping one iteration too early.
  • Assuming a fixed page count instead of following the cursor until it ends.

Where this shows up

This is the loop behind every “sync everything” integration: the customer’s API returns 100 rows at a time behind a cursor and you need all of them. Cursor-following is the robust pagination pattern — unlike offset pagination, it does not drift or skip rows when the data changes underneath you mid-sync.

Finished this one? 0 / 75 Challenges done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges