Merge k Sorted Lists
Real-world version: Merge Shard StreamsThe statement here is our own: the same inputs, outputs and technique.
A monitoring fleet writes its signed temperature readings into shards. You receive streams, a list of those shards. Each shard is already laid out from lowest reading to highest, and a shard may carry nothing at all.
Fold the shards into a single array that runs from lowest reading to highest. Every reading is kept, so a value stored in three shards shows up three times in the result.
The shard count can be far larger than the readings inside any one shard, so pull from all shard fronts together rather than flattening first.
Examples
Example 1
- Input
- streams = [[-8, -1, 4], [-3, 0], [2, 2, 9]]
- Output
- [-8, -3, -1, 0, 2, 2, 4, 9]
Eight readings from three shards line up as one run, and the value 2 stays twice because two shards recorded it.
Example 2
- Input
- streams = [[3, 4, 5], [1, 2]]
- Output
- [1, 2, 3, 4, 5]
The second shard supplies both of the two lowest readings before the first shard contributes anything.
Example 3
- Input
- streams = [[7, 7], [7]]
- Output
- [7, 7, 7]
Repeats spread across shards are all retained, so the result holds three copies.
Constraints
- k == streams.length
- 0 <= k <= 10^4
- 0 <= streams[i].length <= 500
- -10^4 <= streams[i][j] <= 10^4
- Each streams[i] is already in non-decreasing order
- The total number of readings across all shards is at most 10^4
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def merge_streams(streams: list[list[int]]) -> list[int]:public int[] mergeStreams(int[][] streams)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Sort an ArrayReal-world version: Tool Offset OrderingMedium
- Kth Largest Element in an ArrayReal-world version: Kth Highest Daily SwingMedium
- Count Subarrays With Majority Element IReal-world version: Stretches Carried by One CandidateMedium
- K Closest Points to OriginReal-world version: Nearest Survey StakesMedium