Heap / Priority Queue
Hard

Merge K Sorted Lists

Merge k sorted linked lists into one sorted linked list.
Problem Understanding

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.

Example:

  • Input: lists = [[1,4,5],[1,3,4],[2,6]]
  • Output: [1,1,2,3,4,4,5,6]
Algorithm Strategy

Min-Heap Approach (O(N log k))
Instead of comparing the heads of all k lists at every step (which takes O(k)), we can use a Min-Heap.

  1. Initialize: Push the head node of every non-empty list into a Min-Heap.
  2. Iterate: While heap is not empty:
    • Pop the smallest node (root) from heap.
    • Add this node to our result list.
    • If the popped node has a next node, push that next node into the heap.
  3. Result: The result list is sorted.
Interactive Visualization
Step 1 / 1
Empty Heap

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep