#1656

Design an Ordered Stream

Easy
ArrayHash TableDesignData StreamHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a pointer to track the next expected index to return values. This allows us to efficiently collect all contiguous values in a single pass without needing to check the entire array each time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array of size n to store values and a pointer to track the next expected index.
  2. 2Step 2: For each insert, place the value in the array at the index idKey - 1.
  3. 3Step 3: Use the pointer to return the largest possible chunk of contiguous values starting from the pointer.
solution.py12 lines
1class OrderedStream:
2    def __init__(self, n: int):
3        self.stream = [None] * n
4        self.ptr = 0
5
6    def insert(self, idKey: int, value: str):
7        self.stream[idKey - 1] = value
8        result = []
9        while self.ptr < len(self.stream) and self.stream[self.ptr] is not None:
10            result.append(self.stream[self.ptr])
11            self.ptr += 1
12        return result

Complexity note: The time complexity is O(n) because each insertion can potentially lead to a single traversal of the array, but each element is only processed once. The space complexity is O(n) due to the storage of the values.

  • 1Using a pointer to track the next expected index allows for efficient retrieval of contiguous values.
  • 2The problem can be solved using a simple array since the ids are guaranteed to be between 1 and n.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.