Wrapper Over a Paginated Page API That Fetches the Next N Words
LyftSoftware Engineer · OnsiteLast updated
A coding question that wraps an external paginated API, where each page returns a variable number of words, behind a fetch(n) method that returns the next n words in order. It tests handling words left over between calls, requests that span several or empty pages, lazy fetching, the end of the content, and API failures.
You are given an external API that returns content one page at a time, and each page holds a variable number of words. Write a wrapper class around this API that lets callers fetch by word count: each call asks for the next n words and receives them in order, continuing exactly where the previous call stopped.
Assume the external API looks like this (confirm the real shape with the interviewer):
def fetch_page(page: int) -> tuple[list[str], bool]:
"""Return (words, has_more) for page number `page`, counting from 0.
`words` holds the words on that page, in order, and may be of any length.
`has_more` is False on the last page.
"""
Implement:
class WordFetcher:
def __init__(self, fetch_page): ...
def fetch(self, n: int) -> list[str]:
"""Return the next n words. Return fewer only when the content runs out."""
Constraints and Clarifications
- Calls to the external API are slow compared with in-memory work, so the wrapper should call it only when it needs more words.
- The wrapper must never request the same page twice or skip a page.
Clarifying Questions
- Does the API return a list of words, or raw text that the wrapper must split? If raw text, can a word be cut in half at a page boundary?
- Can a page in the middle of the content be empty?
- What should
fetchdo forn = 0, or for a negativen? - What should happen when an API call fails or times out?
Hints
Hint 1
Leftovers: A page rarely holds exactly the number of words a caller asks for. Decide where the words that were fetched but not yet returned live between calls.
Hint 2
Not just one page: A single request can need words from several pages, and it can also be satisfied without calling the API at all.
Follow-up questions
- If the API returns raw text and a word can be split across two pages, how does the wrapper change?
- How would you add retries for transient API failures without losing or duplicating words?
- Two threads share one `WordFetcher`. What can go wrong, and how do you fix it?
- How would you prefetch the next page to hide API latency, and what does that cost?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.