KatInterview

Merge K Sorted Linked-List Runs Into One

Linked ListsAuto-graded · 15 test cases
MediumAuto-gradedLinked Listslinked listsmergesorting

Last 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 from nodes in non-decreasing order.
  • If nodes is 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 ≤ 100
  • 0 ≤ len(nodes) ≤ 2 000
  • boundaries has exactly k + 1 entries; 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.