Merge K Sorted Linked-List Segments Into One
Linked ListsAuto-graded · 15 test casesLast updated
Tests ability to merge multiple sorted runs stored as a flat list of values, exercising the core linked-list merge-sorted-runs technique in pure Python.
Merge K Sorted Segments
You are given a flat list of integers that encodes k sorted segments concatenated back-to-back, together with a list sizes that tells you how many elements belong to each segment.
For example, if values = [3, 7, 1, 4, 9, 2] and sizes = [2, 3, 1], the three segments are:
[3, 7][1, 4, 9][2]
Your task is to merge all segments into a single sorted list and return it.
Each individual segment is guaranteed to be sorted in non-decreasing order. The merged output must also be sorted in non-decreasing order.
Constraints
0 <= len(values) <= 20001 <= len(sizes) <= 50sum(sizes) == len(values)always holds- Each element of
sizesis a positive integer (>= 1) -10^6 <= values[i] <= 10^6- Values may contain duplicates
- If
valuesis empty (andsizescontains one entry equal to0— this case will not appear;sizesalways has positive entries), return[] - If
sizeshas exactly one entry, return a copy ofvalues(already a single sorted segment)
Examples
Example 1
Input: merge_sorted_segments([3, 7, 1, 4, 9, 2], [2, 3, 1])
Output: [1, 2, 3, 4, 7, 9]
Example 2
Input: merge_sorted_segments([5], [1])
Output: [5]
Example 3
Input: merge_sorted_segments([], [])
Output: []
Hints
Hint 1
First, use the sizes list to slice values into k separate sub-lists (segments), then think about how to merge them efficiently.
Hint 2
A min-heap (priority queue) lets you always extract the smallest current front element across all segments in O(log k) time.
Hint 3
Push a tuple of (element_value, segment_index, position_within_segment) onto the heap so you always know which segment to advance next.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Idea: K-Way Merge with a Min-Heap
Because each segment is already sorted, we never need to re-sort any individual segment. We only need to repeatedly pick the globally smallest element from the current fronts of all k segments — exactly the classic k-way merge pattern used internally whenever a merge sort collapses sorted runs.
Step-by-Step
-
Reconstruct segments. Walk through
sizesand slicevaluesinto k sub-lists. This costs O(n) time and O(n) space. -
Seed the heap. Push the first element of every non-empty segment as a tuple
(value, segment_index, position). The tuple form ensures stable comparison even when two values are equal — Python will break ties onsegment_index(an integer), so no custom comparator is needed. -
Drain the heap. Each iteration:
- Pop the minimum
(val, seg_i, pos). - Append
valto the result. - If the same segment has a next element, push it.
The heap never holds more than k entries, so each push/pop is O(log k).
- Pop the minimum
-
Return the result list.
Correctness
At every step the heap contains exactly one "frontier pointer" per non-exhausted segment. The minimum of those pointers is always the globally smallest remaining element (because each segment is sorted). Induction confirms the output is fully sorted.
Complexity
| Time | O(n log k) where n = len(values), k = len(sizes) |
| Space | O(n + k) — O(n) for the output and reconstructed segments, O(k) for the heap |
For the given constraints (n ≤ 2 000, k ≤ 50) this is extremely fast.
Edge Cases
- Single segment — the heap seeds with one entry and drains directly; output equals input.
- All duplicates — ties broken by segment index, producing correct non-decreasing output.
- Single-element segments — each segment is exhausted after its first (and only) pop; handled naturally.
- Negative numbers / large values — integer comparison in the heap handles these correctly.
import heapq
from typing import List
def merge_sorted_segments(values: List[int], sizes: List[int]) -> List[int]:
# Step 1: slice flat list into individual sorted segments
segments = []
idx = 0
for s in sizes:
segments.append(values[idx:idx + s])
idx += s
# Step 2: initialise min-heap with the first element of each segment
# heap entries: (value, segment_index, position_within_segment)
heap = []
for seg_i, seg in enumerate(segments):
if seg:
heapq.heappush(heap, (seg[0], seg_i, 0))
result = []
while heap:
val, seg_i, pos = heapq.heappop(heap)
result.append(val)
next_pos = pos + 1
if next_pos < len(segments[seg_i]):
heapq.heappush(heap, (segments[seg_i][next_pos], seg_i, next_pos))
return result