KatInterview

Streaming Reader for a Page-Based Word Source

Data Structure DesignModel answer
MediumModel answerData Structure Designclass-designbufferingpagination

Last 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 fetch behave for n = 0 or a negative n?
  • 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.