Design an Ordered Stream — LeetCode 1656 Python Solution

EasyDesignArrayHash TableData Stream
Problem
#1656
Pattern
Hash Map
Reading time
4 min

The problem

There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.

Example

Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
Output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
Explanation
// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].

Python solution

Python
class OrderedStream:

    def __init__(self, n: int):
        self.ptr = 1
        self.data = [None] * (n + 1)

    def insert(self, idKey: int, value: str) -> List[str]:
        self.data[idKey] = value
        ans = []
        while self.ptr < len(self.data) and self.data[self.ptr]:
            ans.append(self.data[self.ptr])
            self.ptr += 1
        return ans


# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1656. Design an Ordered Stream is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1656. Design an Ordered Stream?
LeetCode 1656. Design an Ordered Stream is rated Easy on LeetCode.
What is the time complexity of LeetCode 1656. Design an Ordered Stream?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1656. Design an Ordered Stream?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1656. Design an Ordered Stream cover?
LeetCode 1656. Design an Ordered Stream is tagged Design, Array, Hash Table and Data Stream on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview