PythonStudio
Interview Problems

Batching In-Flight Requests

medium · request coalescing

Implement RequestBatcher(capacity), where capacity >= 1 is the maximum unique keys per fake API batch. request(key) returns an integer request ID. IDs start at 0 and increase only when a key is not currently pending. Duplicate requests for a pending key return its existing ID. flush() completes ALL pending requests, returning batches of [key, id] pairs in first-request order, split into groups of at most capacity. After flush, requesting a completed key creates a NEW ID (there is no result cache). flush on an empty batch returns []. This models coalescing and batch dispatch with a fake client; no HTTP, futures, threads, or timers. Examples (JSON; null means Python None): Input: {"capacity": 2, "operations": [["request", ["a"]], ["request", ["b"]], ["request", ["a"]], ["flush", []]]} Output: [0, 1, 0, [[["a", 0], ["b", 1]]]] Input: {"capacity": 1, "operations": [["request", ["x"]], ["flush", []], ["request", ["x"]], ["flush", []]]} Output: [0, [[["x", 0]]], 1, [[["x", 1]]]]

Starter code

class RequestBatcher:

    def __init__(self, capacity: int):
        """Implement this operation according to the statement."""
        pass

    def request(self, key: str) -> int:
        """Implement this operation according to the statement."""
        pass

    def flush(self) -> list[list[list]]:
        """Implement this operation according to the statement."""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler