KatInterview

Merge Pre-Sorted Runs in a Linked List

Linked ListsAuto-graded · 17 test cases
EasyAuto-gradedLinked Listslinked listsmergingsorting

Last 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 → 10
  • 2 → 5 → 9
  • 4 → 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 nodes represents 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

  1. Identify the consecutive ascending runs in nodes.
  2. Repeatedly merge pairs of adjacent runs (like merge sort's merge step) until only one run remains.
  3. 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 nodes is empty, return [].
  • If nodes contains 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.