Merge k Sorted Lists is a classic divide-and-conquer problem that challenges you to efficiently combine multiple sorted linked lists into a single sorted result.

You are given an array of k linked lists, where each list is already sorted in ascending order. Your task is to merge all these lists into one unified sorted linked list and return the head of this merged list.

๐ŸŽฏ Goal: Combine k sorted linked lists efficiently
๐Ÿ“ฅ Input: Array of k sorted linked list heads
๐Ÿ“ค Output: Head of the merged sorted linked list

This problem tests your understanding of merge algorithms, priority queues, and divide-and-conquer strategies. It's frequently asked in technical interviews at top tech companies!

Input & Output

example_1.py โ€” Basic case with three lists
$ Input: lists = [[1,4,5],[1,3,4],[2,6]]
โ€บ Output: [1,1,2,3,4,4,5,6]
๐Ÿ’ก Note: The linked-lists are: [1โ†’4โ†’5], [1โ†’3โ†’4], [2โ†’6]. Merging them in sorted order gives us 1โ†’1โ†’2โ†’3โ†’4โ†’4โ†’5โ†’6.
example_2.py โ€” Empty lists array
$ Input: lists = []
โ€บ Output: []
๐Ÿ’ก Note: No linked lists to merge, so return null/empty.
example_3.py โ€” Array with one empty list
$ Input: lists = [[]]
โ€บ Output: []
๐Ÿ’ก Note: The only list is empty, so the merged result is also empty.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(N log k)

Where N is total nodes and k is number of lists. We merge lists log k times, and each merge processes all N nodes.

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only constant extra space for merge operations. The recursion uses O(log k) stack space, but iterative version uses O(1).

n
2n
โœ“ Linear Space

Constraints

  • k == lists.length
  • 0 โ‰ค k โ‰ค 104
  • 0 โ‰ค lists[i].length โ‰ค 500
  • -104 โ‰ค lists[i][j] โ‰ค 104
  • lists[i] is sorted in ascending order
  • The sum of lists[i].length will not exceed 104
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen