LeetCode 1656: Design an Ordered Stream
Problem Description
Explanation:
- We can use an array to store the values inserted in the stream.
- We keep track of the last inserted id so that when a new pair is inserted, we can identify the largest chunk of currently inserted values that appear next in the order.
- We return this chunk after each insertion.
Algorithm:
- Initialize an array
stream
of sizen
to store the values. - Initialize a variable
ptr
to keep track of the last inserted id. - In the
insert
function: a. Update the value at indexidKey - 1
instream
. b. Check fromptr
ton
in thestream
array to find the largest chunk of values that can be returned. c. Updateptr
toidKey
if the value at indexptr
is not null. d. Return the chunk of values found.
Time Complexity: O(n) for each insert operation where n is the size of the stream.
Space Complexity: O(n) to store the stream of values.
:
Solutions
class OrderedStream {
String[] stream;
int ptr;
public OrderedStream(int n) {
stream = new String[n];
ptr = 0;
}
public List<String> insert(int idKey, String value) {
List<String> result = new ArrayList<>();
stream[idKey - 1] = value;
while (ptr < stream.length && stream[ptr] != null) {
result.add(stream[ptr]);
ptr++;
}
return result;
}
}
Loading editor...