Merge K Sorted Linked-List Runs Into One
Linked ListsAuto-graded · 15 test casesLast updated
Tests pointer manipulation by merging k sorted singly-linked-list segments (given as flat lists with run boundaries) into a single sorted list without allocating extra nodes.
Merge K Sorted Linked-List Runs
You are given a singly-linked list represented as a flat Python list nodes of integers, together with a list boundaries that partitions nodes into k contiguous, individually sorted runs.
boundaries is a list of k+1 indices such that run i occupies nodes[boundaries[i] : boundaries[i+1]]. Every run is sorted in non-decreasing order. Runs may have different lengths and may be empty.
Your task: merge all k runs into a single sorted list and return it as a plain Python list of integers.
You must simulate pointer-based merging — the spirit of the problem is to perform the k-way merge by repeatedly advancing "pointers" (indices) into each run, just as you would manipulate next pointers on real linked-list nodes. (The judge only checks the returned list, so any correct implementation is accepted, but candidates are expected to demonstrate the k-way merge pattern.)
Details
- Return a single Python
list[int]containing all elements fromnodesin non-decreasing order. - If
nodesis empty (or all runs are empty), return[]. - Duplicate values across runs must all appear in the output.
- The relative order of equal elements may be anything (all permutations are equally correct; the judge sorts both sides before comparing).
Constraints
1 ≤ k ≤ 1000 ≤ len(nodes) ≤ 2 000boundarieshas exactlyk + 1entries;boundaries[0] = 0,boundaries[k] = len(nodes), and each entry is non-decreasing.-10^6 ≤ nodes[i] ≤ 10^6- Each run
nodes[boundaries[i]:boundaries[i+1]]is individually sorted in non-decreasing order.
Examples
Example 1
Input: merge_sorted_runs([1, 3, 5, 2, 4, 6], [0, 3, 6])
Output: [1, 2, 3, 4, 5, 6]
Example 2
Input: merge_sorted_runs([1, 1, 2, 3, 1, 4], [0, 2, 4, 6])
Output: [1, 1, 1, 2, 3, 4]
Example 3
Input: merge_sorted_runs([], [0])
Output: []
Hints
Hint 1
Use a min-heap (priority queue) seeded with the first element of each non-empty run. Each heap entry should store (value, run_index, position_within_run) so you can advance the pointer when an element is popped.
Hint 2
After popping the minimum element, check whether the corresponding run still has more elements; if so, push the next element from that run onto the heap.
Hint 3
Handle edge cases: empty runs should simply be skipped when initialising the heap, and k=1 means you can return the single run directly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: K-Way Merge with a Min-Heap
Intuition
Each of the k runs is already sorted. This is identical to merging k sorted linked lists: at every step we want the globally smallest element among all "current heads" of the k lists. A min-heap (priority queue) gives us the minimum in O(log k) time.
Algorithm
- Initialise — push the first element of every non-empty run onto the heap as a tuple
(value, run_index, position). The position plays the role of anext-pointer into the flatnodesarray. - Merge loop — while the heap is non-empty:
- Pop the smallest
(val, run_idx, pos). - Append
valtoresult. - If the run still has more elements (i.e.
pos + 1 < boundaries[run_idx + 1]), push the next element from that run.
- Pop the smallest
- Return
result.
Correctness
At every iteration the heap holds exactly one "current head" per non-exhausted run. The minimum across all heads is the next element in the globally sorted order, which is exactly what a k-way merge produces.
Duplicates are handled naturally: equal values in different runs will both be pushed and popped in separate heap entries.
Complexity
| Time | O(N log k) where N = len(nodes) and k = number of runs. Each element is pushed and popped once; each heap operation costs O(log k). |
| Space | O(k) for the heap + O(N) for the output list. |
Reference Solution
import heapq
from typing import List
def merge_sorted_runs(nodes: List[int], boundaries: List[int]) -> List[int]:
if not nodes:
return []
k = len(boundaries) - 1
heap = []
# Seed the heap with the first element of each non-empty run.
for i in range(k):
start, end = boundaries[i], boundaries[i + 1]
if start < end: # run is non-empty
heapq.heappush(heap, (nodes[start], i, start))
result = []
while heap:
val, run_idx, pos = heapq.heappop(heap)
result.append(val)
next_pos = pos + 1
if next_pos < boundaries[run_idx + 1]: # run has more elements
heapq.heappush(heap, (nodes[next_pos], run_idx, next_pos))
return result
Edge Cases Handled
- Empty
nodes— returns[]immediately. - All-empty runs (
boundarieswith equal adjacent entries) — no items are seeded; the loop doesn't execute;[]is returned. - Single run (k = 1) — the heap simply pops each element in order, returning the run unchanged.
- Single element — works without special handling.
- All duplicates — each copy is pushed/popped independently, all appear in the output.