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.
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 takenvalues.String[] insert(int idKey, String value)Inserts the pair(idKey, value)into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.
Examples
Example 1:
| |
Constraints:
1 <= n <= 10001 <= id <= nvalue.length == 5valueconsists only of lowercase letters.- Each call to
insertwill have a uniqueid. - Exactly
ncalls will be made toinsert.
Solution
Method 1 - Using an array
The problem requires building a stream that can receive a series of (idKey, value) pairs and return the values in increasing order of their IDs. The goal is to manage the stream such that after each insertion, the largest possible chunk of values, starting from the smallest unprocessed ID, is returned.
Approach
- Initialization: Create an array to hold the values corresponding to each ID. Initialize a pointer to the smallest unprocessed ID (starting from 1).
- Insertion:
- Insert the value into the appropriate position in the array based on the given
idKey. - Start from the pointer and collect the largest chunk of consecutive values that have been inserted.
- Return the collected chunk and update the pointer to the next unprocessed ID.
- Insert the value into the appropriate position in the array based on the given
Code
| |
| |
Complexity
- ⏰ Time complexity: The time complexity for both the constructor and the
insertmethod isO(n)in the worst case, wherenis the number of elements in the stream. - 🧺 Space complexity:
O(n)due to the storage required for the array of values.