[LeetCode]#1656. Design an Ordered Stream
Environment: Python 3.7
Key technique: self, while
There is a stream of n
(id, value)
pairs arriving in an arbitrary order, where id
is an integer between 1
and n
and value
is a string. No two pairs have the same id
.
Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.
Implement the OrderedStream
class:
OrderedStream(int n)
Constructs the stream to taken
values.String[] insert(int id, String value)
Inserts the pair(id, value)
into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.
Example:

Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
Output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
Analysis:
I am not so good as below code. I output every step and try analysis them.
- Default data and ptr as below.

2. insert 3 and “ccccc” and find id != self.ptr.
3. Return []

4. Insert 1 and “aaaaa”.
5. Find self.data[2] is nothing.
6. return self.data[1:2] and is ‘aaaaa’

7. insert 2 and ‘bbbbb’
8. Find self.data[4] is nothing.
9. return self.data[2:4] and is ‘bbbbb’, ‘ccccc’

Solution:
class OrderedStream:
def __init__(self, n: int):
self.data = [None] * (n + 1)
self.ptr = 1
def insert(self, id: int, value: str):
self.data[id] = value
if id == self.ptr:
while self.ptr < len(self.data) and self.data[self.ptr]:
self.ptr += 1
return self.data[id:self.ptr]
return []
Submissions:

Reference: