Merge k Sorted Lists - Problem
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
๐ฏ 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!
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.
โก 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).
โ 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code