KatInterview

Merge K Sorted Linked-List Segments Into One

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

Last updated

Tests ability to merge multiple sorted runs stored as a flat list of values, exercising the core linked-list merge-sorted-runs technique in pure Python.

Merge K Sorted Segments

You are given a flat list of integers that encodes k sorted segments concatenated back-to-back, together with a list sizes that tells you how many elements belong to each segment.

For example, if values = [3, 7, 1, 4, 9, 2] and sizes = [2, 3, 1], the three segments are:

  • [3, 7]
  • [1, 4, 9]
  • [2]

Your task is to merge all segments into a single sorted list and return it.

Each individual segment is guaranteed to be sorted in non-decreasing order. The merged output must also be sorted in non-decreasing order.

Constraints

  • 0 <= len(values) <= 2000
  • 1 <= len(sizes) <= 50
  • sum(sizes) == len(values) always holds
  • Each element of sizes is a positive integer (>= 1)
  • -10^6 <= values[i] <= 10^6
  • Values may contain duplicates
  • If values is empty (and sizes contains one entry equal to 0 — this case will not appear; sizes always has positive entries), return []
  • If sizes has exactly one entry, return a copy of values (already a single sorted segment)

Examples

Example 1

Input: merge_sorted_segments([3, 7, 1, 4, 9, 2], [2, 3, 1])

Output: [1, 2, 3, 4, 7, 9]

Example 2

Input: merge_sorted_segments([5], [1])

Output: [5]

Example 3

Input: merge_sorted_segments([], [])

Output: []

Hints

Hint 1

First, use the sizes list to slice values into k separate sub-lists (segments), then think about how to merge them efficiently.

Hint 2

A min-heap (priority queue) lets you always extract the smallest current front element across all segments in O(log k) time.

Hint 3

Push a tuple of (element_value, segment_index, position_within_segment) onto the heap so you always know which segment to advance next.