Streaming Reader for a Page-Based Word Source
Data Structure DesignModel answerLast updated
Build a class that wraps a slow, paginated word API and serves exact word counts per call, keeping leftovers between calls and fetching pages lazily.
A remote service exposes a body of text as a sequence of pages. Pages are numbered from 0, and each page holds a list of words whose length can differ from page to page, including zero. Your task is to put a thin class in front of this service so that callers can ask for words by count instead of by page.
The service function has this shape (confirm the real signature before relying on it):
def fetch_page(page: int) -> tuple[list[str], bool]:
"""Return (words, has_more) for page number `page`, starting at 0.
`words` is the ordered list of words on that page and can have any length.
`has_more` is False only for the final page.
"""
Implement this class:
class WordFetcher:
def __init__(self, fetch_page): ...
def fetch(self, n: int) -> list[str]:
"""Return the next n words in order.
Return fewer than n only if the content has run out."""
Each call to fetch must resume exactly where the previous call ended. Over the lifetime of the object, every word is returned once, in the original order.
Requirements
- Calling the service is expensive compared with in-memory work, so only request a page when the words already held are not enough for the current call.
- Never request the same page twice and never skip a page.
Points to settle before coding
- Does the service return a list of words, or raw text you have to split? If it is raw text, can a word be split across a page boundary?
- Can a page in the middle of the content be empty?
- How should
fetchbehave forn = 0or a negativen? - What should happen if a service call fails or times out?
Explain your design, state the complexity, and write the code. Describe how you would test it.
Hints
Hint 1
Think about what must persist between calls: the next page number, the words already downloaded but not yet handed out, and a flag saying the content is finished.
Hint 2
A single call may need zero, one, or many pages. Use a loop that keeps pulling pages while the buffer is too small and the content has not ended, rather than assuming one page is enough.
Hint 3
Removing items from the front of a Python list is O(k) per removal. Use a collections.deque (or an index into the buffer) so leftovers are consumed cheaply, and make sure an empty page does not stop the loop early; only has_more=False should.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The wrapper is a small state machine with three pieces of state:
_next_page: the number of the next page to request, starting at 0._buffer: words that have been downloaded but not yet returned. Acollections.dequegives O(1) pops from the left._done: set to True once a page reportshas_more = False.
fetch(n) runs in two phases:
- Fill. While the buffer holds fewer than
nwords and the content is not finished, request_next_page, extend the buffer with its words, increment_next_page, and recordhas_more. - Drain. Pop up to
nwords from the left of the buffer and return them.
Because the fill loop condition checks only buffer size and the _done flag, it naturally handles all the awkward cases:
- Request spans several pages: the loop simply iterates more than once.
- Request ends mid-page: the surplus stays in the buffer for the next call, so no word is lost or repeated.
- Empty pages: an empty list adds nothing, the loop continues, and only
has_more = Falseends it. Treating an empty page as the end is a common bug. - Content exhausted:
_doneis True, the loop does not run, and the drain returns whatever remains (possibly an empty list). No further API call is made. - Lazy fetching: if the buffer already holds at least
nwords, the loop body never executes, so there is no API call.
Code
from collections import deque
class WordFetcher:
def __init__(self, fetch_page):
self._fetch_page = fetch_page
self._next_page = 0
self._buffer = deque()
self._done = False
def fetch(self, n: int) -> list[str]:
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return []
while len(self._buffer) < n and not self._done:
words, has_more = self._fetch_page(self._next_page)
# Advance only after a successful call, so a failure can be retried.
self._next_page += 1
self._buffer.extend(words)
if not has_more:
self._done = True
take = min(n, len(self._buffer))
return [self._buffer.popleft() for _ in range(take)]
Complexity
- Time: O(n + W) per call, where W is the number of words in the pages fetched during that call. Across the whole lifetime, each word is appended once and popped once, so total work is linear in the content size, plus one API call per page.
- Space: O(n + P) where P is the largest page size, since the buffer holds at most the requested words plus one page of leftovers.
- API calls: exactly one per page, and only when needed.
Design decisions and trade-offs
- Deque versus list slicing.
buffer = buffer[n:]copies the remainder on every call, which becomes quadratic for many small calls over a large page. A deque, or a list plus a read index, avoids that. - Advance the page counter only after success. If
fetch_pageraises, the exception propagates and_next_pageis unchanged, so the caller can retry without skipping or duplicating a page. Words already returned in earlier calls are unaffected. One subtle point: if the failure happens mid-call after some pages were buffered, those words stay in the buffer and will be served on the retry, so nothing is lost. - Failure policy. The wrapper can either let exceptions propagate (simplest, caller decides) or retry with exponential backoff for transient errors. Make the choice explicit and keep it out of the core logic, for example by wrapping
fetch_pagein a retry decorator. - Prefetching. If latency dominates, a background thread could prefetch the next page while the caller processes the current words. This adds locking and complexity, so mention it as an extension rather than the default.
- Thread safety. The class as written is not safe for concurrent callers. Guard
fetchwith a lock if it must be shared. - Raw text instead of word lists. If pages are raw strings and a word can straddle a boundary, keep a trailing partial token: split the page, hold back the last token unless the page ends in whitespace or is the final page, and prepend it to the next page. Without this, you would return a broken word.
- Negative or zero n. Return an empty list for 0. Raising
ValueErrorfor negatives is reasonable; returning an empty list is also defensible if documented.
Testing
Use a fake fetch_page backed by a list of pages and a call counter. Cover:
- Pages of varied sizes, such as
[3, 0, 5, 1, 0, 2], with requests of size 1, 2, 4, and larger than the total. - A request exactly equal to the buffered amount (no extra API call).
- A request spanning several pages including empty ones in the middle.
- Calling
fetchafter the end: returns[]and the call counter does not increase. - A single-page source and a source whose first page is empty.
- Asserting that the sequence of requested page numbers is
0, 1, 2, ...with no repeats or gaps. - An injected failure on page k, followed by a retry that succeeds and yields the correct continuation.
- A property test: concatenating the results of random
nvalues must equal the flattened content.
Common mistakes
- Stopping when a page is empty instead of when
has_moreis False. - Fetching a page eagerly "just in case" when the buffer already suffices.
- Discarding the surplus of a page instead of keeping it for the next call.
- Incrementing the page counter before the call succeeds.
- Using
list.pop(0)or repeated slicing, producing quadratic behavior. - Calling the API again after the final page, because the
has_moreflag was never stored.