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: Problem OverviewInput: k = 3 sorted lists14513426⬇ MERGE ALGORITHM ⬇Combine while maintaining sorted orderOutput: Single sorted list11234456Challenge:• Maintain sorted order• Handle k lists efficiently• Avoid sorting from scratchSolutions:• Brute Force: O(n log n)• Min Heap: O(n log k)• Divide & Conquer: O(n log k)
Understanding the Visualization
1
Input
k sorted linked lists with total n nodes
2
Process
Merge strategy preserving sorted order
3
Output
Single sorted linked list containing all nodes
Key Takeaway
🎯 Key Insight: Leverage that individual lists are already sorted - use divide and conquer to merge pairwise rather than sorting all values from scratch
Asked in
Amazon 87 Facebook 45 Google 42 Microsoft 38 Apple 25
89.5K 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