File: design-an-ordered-stream/solution.py

Date: 2026-06-06

Time: 16:16

Purpose

This file implements LeetCode 1656 — Design an Ordered Stream. It solves the problem of buffering out-of-order inserts and releasing values only when a contiguous prefix is available — essentially a reordering buffer with a read pointer.

Key Components

OrderedStream

A class with two methods:

Patterns

Monotonic pointer scan: The pointer only moves forward, never backward. Each element is visited by the pointer at most once across all insert calls, giving O(n) total pointer work amortized over n inserts.

Pre-allocated buffer with sentinel: Uses None as a sentinel to distinguish filled vs. unfilled slots. This avoids needing a separate "filled" set or bitmap.

Dependencies

Imports: Only List from typing — no external or project dependencies.

Imported by: design-an-ordered-stream/test_solution.py. The massive "Imported By" list in the prompt is an artifact of the repo's test infrastructure, not actual imports of this module.

Flow

1. Caller creates OrderedStream(n) — a buffer of n slots and a pointer at 0.

2. Each insert(idKey, value) writes to slot idKey - 1.

3. The while loop drains all contiguous non-None slots starting at self.ptr.

4. If the inserted slot is ahead of the pointer (gap exists), the loop body never executes and an empty list is returned.

5. If the inserted slot fills the gap the pointer was waiting on, the loop flushes all contiguous ready values.

Invariants

Error Handling

None. The code trusts that callers respect the LeetCode contract (valid idKey range, no duplicates). An out-of-range idKey would raise IndexError from the list access.

Topics to Explore

Beliefs