Sort a Linked List Using Merge Sort
Linked ListsAuto-graded · 17 test casesLast updated
Tests pointer manipulation by implementing bottom-up merge sort on a singly linked list represented as a dict-based node structure.
Sort a Linked List Using Merge Sort
You are given a singly linked list encoded as a list of integers (in order from head to tail). Your task is to sort it in non-decreasing order by implementing a merge-sort strategy that operates on the list's pointer structure — specifically by merging sorted runs.
The list is represented using Python dictionaries, where each node is {"val": int, "next": node | None}. However, to keep the interface JSON-compatible, your function receives and returns a plain Python list[int], and you must reconstruct the linked-list nodes internally, sort using pointer manipulation (merging sorted runs), and then read off the values into a returned list.
Task
Implement merge_sort_linked_list(values: list[int]) -> list[int] that:
- Builds a singly linked list from
values(head isvalues[0]). - Sorts the list in non-decreasing order by repeatedly merging sorted runs of increasing length (bottom-up merge sort): start with run length 1, then 2, 4, 8, … until the entire list is sorted.
- Returns the sorted values as a
list[int].
Bottom-Up Merge Sort on a Linked List
In each pass, scan the list from left to right:
- Extract two consecutive runs of length
size(the second run may be shorter). - Merge the two sorted runs using pointer manipulation (no auxiliary arrays).
- Attach the merged segment to the growing output list.
- Double
sizeafter each full pass over the list. - Repeat until
size ≥ length of the list.
Constraints
0 ≤ len(values) ≤ 2000-10^6 ≤ values[i] ≤ 10^6- Duplicate values are allowed.
- If
valuesis empty, return[]. - If
valueshas one element, return it unchanged. - The returned list must be sorted in non-decreasing order (stable sort is not required; any valid sorted order is accepted).
Examples
Example 1
Input: merge_sort_linked_list([5, 3, 1, 4, 2])
Output: [1, 2, 3, 4, 5]
Example 2
Input: merge_sort_linked_list([7, -2, 0, 3, -5, 1])
Output: [-5, -2, 0, 1, 3, 7]
Example 3
Input: merge_sort_linked_list([])
Output: []
Hints
Hint 1
Build a dummy head node to simplify pointer manipulation when attaching merged segments during each pass.
Hint 2
To split a run of length `size` from the current position, walk `size - 1` steps forward and sever the `next` pointer — store it before severing so you can continue scanning.
Hint 3
After each full pass, set `size *= 2` and restart from the (new) head — use a dummy node so the new head can change without special-casing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
A standard top-down merge sort on a linked list requires O(log n) stack space for recursion. The bottom-up variant avoids recursion entirely: it performs log₂(n) passes over the list, each time merging adjacent sorted runs of a fixed size (1, 2, 4, 8, …). This is ideal for linked lists because splitting and merging are pure pointer operations — no random access or auxiliary arrays needed.
Algorithm
-
Build the linked list from the input array. Each node is a plain Python dict
{"val": int, "next": node | None}. -
Outer loop —
sizedoubles each iteration (1, 2, 4, …) untilsize ≥ n. Each iteration is one pass. -
Inner loop — scan from the current head:
- Walk
sizenodes to extract the left run; sever its tail pointer. - Walk another
sizenodes for the right run (may be shorter); sever its tail pointer. Save the continuation (cur) from the right run's tail. - Merge the two sorted runs via the standard two-pointer merge, returning a new head.
- Append the merged segment to a growing output chain using a dummy head node so we never special-case the first segment.
- Repeat until
curisNone.
- Walk
-
After each pass the dummy head's
nextis the new (partially sorted) head. -
After log₂(n) passes the list is fully sorted. Read off values into a Python list and return.
Correctness
- After pass
kevery contiguous block of 2^k nodes is sorted. - By the final pass the entire list (≤ 2^k nodes) is one sorted block.
- The merge step is the classic O(a+b) merge of two sorted sequences, correct by induction.
Complexity
| Value | |
|---|---|
| Time | O(n log n) — O(log n) passes, each O(n) |
| Space | O(n) to build the node dicts; O(1) extra pointer space during sorting |
Reference Solution
from typing import Optional
def merge_sort_linked_list(values: list[int]) -> list[int]:
if not values:
return []
# Build linked list
nodes = [{"val": v, "next": None} for v in values]
for i in range(len(nodes) - 1):
nodes[i]["next"] = nodes[i + 1]
head = nodes[0]
def merge(l1, l2):
dummy = {"val": 0, "next": None}
cur = dummy
while l1 and l2:
if l1["val"] <= l2["val"]:
cur["next"] = l1
l1 = l1["next"]
else:
cur["next"] = l2
l2 = l2["next"]
cur = cur["next"]
cur["next"] = l1 if l1 else l2
return dummy["next"]
n = len(values)
size = 1
while size < n:
dummy_head = {"val": 0, "next": None}
tail = dummy_head
cur = head
while cur:
left = cur
left_tail = left
for _ in range(size - 1):
if left_tail["next"]:
left_tail = left_tail["next"]
else:
break
right = left_tail["next"]
left_tail["next"] = None
if right:
right_tail = right
for _ in range(size - 1):
if right_tail["next"]:
right_tail = right_tail["next"]
else:
break
cur = right_tail["next"]
right_tail["next"] = None
else:
cur = None
merged = merge(left, right)
tail["next"] = merged
while tail["next"]:
tail = tail["next"]
head = dummy_head["next"]
size *= 2
result = []
node = head
while node:
result.append(node["val"])
node = node["next"]
return result