Design an Ordered Stream - Problem
There is a stream of n pairs (idKey, value) 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 take n values.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.
Input & Output
Example 1 — Basic Stream Operations
$
Input:
n = 5, operations = [[3,"ccccc"],[1,"aaaaa"],[2,"bbbbb"],[5,"eeeee"],[4,"ddddd"]]
›
Output:
[[],["aaaaa"],["aaaaa","bbbbb","ccccc"],[],["ddddd","eeeee"]]
💡 Note:
Insert (3,"ccccc"): ptr=1, arr[1] is empty, return []. Insert (1,"aaaaa"): ptr=1, arr[1]="aaaaa", return ["aaaaa"], ptr=2. Insert (2,"bbbbb"): ptr=2, found consecutive values at positions 2,3, return ["bbbbb","ccccc"], ptr=4.
Example 2 — Sequential Order
$
Input:
n = 3, operations = [[1,"first"],[2,"second"],[3,"third"]]
›
Output:
[["first"],["second"],["third"]]
💡 Note:
Each insert returns exactly one value since they arrive in order: ptr advances one position each time.
Example 3 — Reverse Order
$
Input:
n = 3, operations = [[3,"third"],[2,"second"],[1,"first"]]
›
Output:
[[],[],["first","second","third"]]
💡 Note:
First two inserts return [] since ptr=1 is not filled. When (1,"first") arrives, all consecutive values 1,2,3 are returned.
Constraints
- 1 ≤ n ≤ 1000
- 1 ≤ idKey ≤ n
- value.length == 5
- value consists only of lowercase letters
- Each call to insert will have a unique idKey
Visualization
Tap to expand
Understanding the Visualization
1
Stream Setup
Create stream of size n=5, pointer starts at position 1
2
Insert Operations
Insert (id,value) pairs in arbitrary order
3
Return Chunks
Return largest consecutive chunk from current pointer position
Key Takeaway
🎯 Key Insight: Use array for direct access and pointer to efficiently detect consecutive chunks
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code