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 interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. The GraderCharacter joke · No posting date

    Edge case? Never met her.

  2. InterviewerCharacter joke · No posting date

    Walk me through your thinking. No, not out loud. In code. In silence. While I watch.

  3. Me at 2amCharacter joke · No posting date

    My code works. I have no idea why. I am afraid to touch it. I am going to bed.