Merge Pre-Sorted Runs in a Linked List
Linked ListsAuto-graded · 17 test casesLast updated
Tests pointer manipulation by merging a singly-linked list that is already partitioned into consecutive ascending runs into a single sorted list.
Merge Pre-Sorted Runs in a Linked List
You are given a singly-linked list whose nodes are already arranged in consecutive ascending runs. A run is a maximal sequence of nodes whose values are strictly increasing (each value is strictly greater than the previous one within the run).
For example, the list [3, 7, 10, 2, 5, 9, 4, 8] has three runs:
3 → 7 → 102 → 5 → 94 → 8
Your task is to merge all of these runs into a single non-decreasing linked list and return it.
Because the input is represented as a plain Python list (for automatic judging), your function receives a list[int] and must return a list[int].
Your implementation must simulate the linked-list merging process described below — the spirit of the problem is pointer manipulation, not a one-liner sort.
Representation
- The input list
nodesrepresents the values of the linked list in order. - The output must be the values of the fully merged linked list, in order, as a Python list.
Task
- Identify the consecutive ascending runs in
nodes. - Repeatedly merge pairs of adjacent runs (like merge sort's merge step) until only one run remains.
- Return the resulting list of values.
Tie-breaking / Stability
- Equal values may appear in the input. When two runs both contain the same value, the element from the earlier run (lower run index) must appear first in the output.
Constraints
0 ≤ len(nodes) ≤ 2000-10^6 ≤ nodes[i] ≤ 10^6- Values within each run are strictly increasing.
- Equal values may appear across different runs.
- If
nodesis empty, return[]. - If
nodescontains a single element, return that element in a list.
Examples
Example 1
Input: merge_sorted_runs([3, 7, 10, 2, 5, 9, 4, 8])
Output: [2, 3, 4, 5, 7, 8, 9, 10]
Example 2
Input: merge_sorted_runs([1, 3, 5, 2, 4, 6])
Output: [1, 2, 3, 4, 5, 6]
Example 3
Input: merge_sorted_runs([])
Output: []
Hints
Hint 1
First scan the list once to split it into individual runs (each run ends where the next value is not strictly greater than the current one).
Hint 2
Once you have a list of runs, repeatedly pass through them and merge consecutive pairs — this is the classic bottom-up merge-sort merge phase applied to pre-existing runs.
Hint 3
When merging two runs, use the standard two-pointer merge: advance the pointer from the run with the smaller front element, and break ties by taking from the earlier (left) run first to preserve stability.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The input list is already broken into strictly-increasing runs. The problem is therefore a classic bottom-up merge task:
- Identify the runs with a single left-to-right scan — a new run starts whenever
nodes[i] <= nodes[i-1]. - Pairwise-merge adjacent runs repeatedly until only one run remains. This mirrors the merge phase of bottom-up merge sort.
Correctness
- Each individual run is sorted, so a standard two-pointer merge produces a sorted result.
- After one full pass of pairwise merges the number of runs halves; after ⌈log₂(R)⌉ passes (where R is the initial number of runs) a single sorted run remains.
- Stability: when two elements are equal we always take from the left (earlier) run first (
a[i] <= b[j]), preserving the original run order for ties.
Complexity
| Value | |
|---|---|
| Time | O(n log R) ≤ O(n log n), where n = len(nodes), R = number of runs |
| Space | O(n) auxiliary for the merged lists |
In the best case (already sorted, R = 1) the algorithm does O(n) work just to detect one run and return it immediately.
Reference Solution
from typing import List
def merge_sorted_runs(nodes: List[int]) -> List[int]:
if not nodes:
return []
# Step 1: Split into runs (each run is strictly increasing).
runs = []
start = 0
for i in range(1, len(nodes)):
if nodes[i] <= nodes[i - 1]: # run boundary
runs.append(nodes[start:i])
start = i
runs.append(nodes[start:]) # last run
# Step 2: Bottom-up pairwise merging until one run remains.
def merge(a: List[int], b: List[int]) -> List[int]:
result = []
i = j = 0
while i < len(a) and j < len(b):
# Stability: equal value → take from the earlier (left) run.
if a[i] <= b[j]:
result.append(a[i]); i += 1
else:
result.append(b[j]); j += 1
result.extend(a[i:])
result.extend(b[j:])
return result
while len(runs) > 1:
merged = []
for k in range(0, len(runs), 2):
if k + 1 < len(runs):
merged.append(merge(runs[k], runs[k + 1]))
else:
merged.append(runs[k]) # odd run out, carry forward
runs = merged
return runs[0]