Resumable Batch Reader for a Linked Page Feed
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a stateful reader that serves batches of N items in order from a chained page feed, buffering surplus items and handling empty pages, loops and the end of the feed.
Resumable Batch Reader for a Linked Page Feed
A remote feed publishes its items in pages. Each page is stored under a string token and holds two fields:
items: a list of values, in feed order.nextPage: the token of the following page, ornullwhen this page is the last one.
You are given a lookup table page_map that stands in for the remote feed: it maps each token to its page. You must simulate a stateful reader that starts at start_token and hands out items in batches. State carries over between calls: each request continues exactly where the previous one stopped.
Operations
You receive two parallel lists, operations and arguments. The i-th entry of operations is an operation name, and the i-th entry of arguments is its argument list. The only operation is "fetchN", whose argument list is [n].
Process the operations in order against one reader that lives for the whole run. Return a list containing one result per "fetchN" operation, in order. Each result is itself a list of items. Operations with any other name are ignored and add nothing to the output.
Behavior of fetchN(n)
- If
n <= 0, return[]and do not touch the feed. - Otherwise return the next
nnot-yet-returned items in feed order. If fewer thannremain in the whole feed, return all of them. - Items already downloaded but not yet returned must be served before any new page is downloaded. Do not download more pages than needed to satisfy the request. Stop as soon as at least
nitems are available. - When a downloaded page holds more items than the current request needs, the surplus must be kept for later calls. Nothing may be dropped or repeated, and order must be preserved across pages.
- A page with an empty
itemslist is still a normal page. If itsnextPageis non-null, keep going to the next page. - The feed has ended when a downloaded page has no
nextPage(missing ornull), or when itsnextPageis the literal string"null". After that, no further downloads happen, but any buffered items can still be returned by later calls. Once the buffer is empty as well, calls return[]. - If a page lacks an
itemsfield, treat it as having no items. - If the token to download is not a key of
page_map(including anullstart token), treat it as an empty page that ends the feed. - Loop protection: the reader remembers every token it has downloaded. If it needs more items and the next token to download was already downloaded earlier, it treats the feed as ended without downloading again. Items already buffered stay available.
Constraints
0 <= len(operations) == len(arguments) <= 10^4- Each
"fetchN"argument list holds exactly one integern, with-10^4 <= n <= 10^4. - The total number of items across all pages is at most
10^5. - Tokens are strings (the start token may also be
null). Items can be any JSON values and are returned unchanged. - Calls are strictly sequential, so there is no concurrency to handle.
Examples
Example 1
Input: run_paged_reader('p1', {'p1': {'items': [1, 2], 'nextPage': 'p2'}, 'p2': {'items': [3, 4], 'nextPage': None}}, ['fetchN', 'fetchN', 'fetchN'], [[3], [2], [0]])
Output: [[1, 2, 3], [4], []]
Example 2
Input: run_paged_reader('a', {'a': {'items': [], 'nextPage': 'b'}, 'b': {'items': [7], 'nextPage': None}}, ['fetchN', 'fetchN'], [[1], [2]])
Output: [[7], []]
Hints
Hint 1
The reader needs three things that survive between calls: the next token to download, a buffer of downloaded-but-unreturned items, and a flag saying the feed has ended.
Hint 2
Serve from the buffer first. Download pages in a loop only while the buffer holds fewer than n items and the feed has not ended. Then slice off the first n items and keep the rest.
Hint 3
Keep a set of tokens already downloaded to detect cycles, and check it before each download. Also remember that an empty page with a next token is not the end, but a missing, null or "null" next token is.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The reader keeps three pieces of state between calls:
token: the next page to download.buffer: items downloaded but not yet handed out.ended: whether the feed is finished, plus aseenset of tokens already downloaded.
For each fetchN(n):
- If
n <= 0, return[]immediately, with no downloads. - While the buffer has fewer than
nitems and the feed has not ended:- If the next token was already downloaded, mark the feed as ended and stop (loop protection).
- Record the token and download its page. A missing token or a
nulltoken is treated as an empty terminal page. - Append the page's items to the buffer.
- If the page's
nextPageis missing,nullor"null", mark the feed as ended. Otherwise advancetoken.
- Cut the first
nitems off the buffer as the result (fewer if the buffer is shorter) and keep the rest.
Operations other than "fetchN" are skipped, and results are collected in order.
Why it is correct
- Items only ever enter the buffer in page order, and they leave only from the front. This preserves feed order across pages and calls, and nothing is lost or repeated.
- Pages are downloaded only while the buffer is too small, so the buffer is always drained before any new download, and surplus items are kept for the next call.
- An empty page with a next token adds nothing to the buffer but advances the token, so the loop continues past it. Only a missing,
nullor"null"next token ends the feed. - The
seenset guarantees every token is downloaded at most once, so cyclic page chains terminate. Anything already buffered is still returned. - Once the feed has ended, the loop is skipped, so later calls only drain the buffer and eventually return
[].
Complexity
Each page is downloaded at most once, and each item is appended once and sliced out once. Slicing the buffer can copy the remaining surplus, so the worst case is O(P + I + Q·B), where P is the number of pages, I the number of items, Q the number of operations and B the buffer size. Using an index pointer or a deque would bring it down to O(P + I + Q). Space is O(P + I) for the seen set and buffer.
Reference solution
from typing import Dict, List
def run_paged_reader(start_token: str, page_map: Dict[str, Dict], operations: List[str], arguments: List[List[int]]) -> List:
class Reader:
def __init__(self, token, pages):
self.token = token
self.pages = pages
self.buffer = []
self.ended = False
self.seen = set()
def download(self, token):
if token is None or token not in self.pages:
return {"items": [], "nextPage": None}
return self.pages[token]
def fetch_n(self, n):
if n <= 0:
return []
while len(self.buffer) < n and not self.ended:
if self.token in self.seen:
self.ended = True
break
if self.token is not None:
self.seen.add(self.token)
page = self.download(self.token)
self.buffer.extend(page.get("items", []))
nxt = page.get("nextPage")
if nxt is None or nxt == "null":
self.ended = True
self.token = None
else:
self.token = nxt
out = self.buffer[:n]
self.buffer = self.buffer[n:]
return out
reader = Reader(start_token, page_map)
results = []
for op, args in zip(operations, arguments):
if op == "fetchN":
results.append(reader.fetch_n(args[0]))
return results