You are given an array of k linked-lists lists, where each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

Input & Output

Example 1 — Three Sorted 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 results in [1→1→2→3→4→4→5→6]
Example 2 — Empty Lists Array
$ Input: lists = []
Output: []
💡 Note: No lists to merge, return empty result
Example 3 — Single Empty List
$ Input: lists = [[]]
Output: []
💡 Note: Only one empty list, result is empty

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

Visualization

Tap to expand
Merge k Sorted Lists INPUT k = 3 sorted linked lists List 1: 1 4 5 null List 2: 1 3 4 null List 3: 2 6 null Input Array: [[1,4,5],[1,3,4],[2,6]] Each list already sorted in ascending order ALGORITHM STEPS Divide and Conquer 1 Divide Split k lists into pairs 2 Merge Pairs Merge two lists at a time 3 Recurse Repeat until one list left 4 Return Return merged sorted list Merge Process: L1 L2 L3 L1+L2 L3 Final Merged FINAL RESULT Merged Sorted Linked List: 1 1 2 3 4 4 5 6 null Output Array: [1,1,2,3,4,4,5,6] OK - Sorted! Complexity Analysis: Time: O(N log k) Space: O(log k) for recursion N = total nodes, k = lists Key Insight: Divide and Conquer reduces the problem from k merges to log(k) levels. Instead of merging one list at a time (O(kN)), we pair up lists and merge them in parallel-like fashion. This approach is similar to merge sort and achieves optimal O(N log k) time complexity. TutorialsPoint - Merge k Sorted Lists | Divide and Conquer Approach
Asked in
Amazon 87 Facebook 45 Google 42 Microsoft 38 Apple 25
89.6K Views
Very High Frequency
~25 min Avg. Time
2.8K 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