KatInterview

Sort a Linked List Using Merge Sort

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked listsmerge sortpointer manipulation

Last 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:

  1. Builds a singly linked list from values (head is values[0]).
  2. 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.
  3. 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 size after 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 values is empty, return [].
  • If values has 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.