#23

Merge k Sorted Lists

HardHeapHas vizLinked ListHeap
Related studio

Problem

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 1

Input: lists = [[1,4,5],[1,3,4],[2,6]]

Output: [1,1,2,3,4,4,5,6]

Merging the three sorted lists yields one sorted list.

Example 2

Input: lists = []

Output: []

Nothing to merge.

Example 3

Input: lists = [[]]

Output: []

One empty list.

Constraints

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length will not exceed 10^4.
Loading visualization…

Explanation

Merge k Sorted Lists is a Hard interview problem tagged [Linked List, Heap]. The winning approach is typically **Heap**.

Intuition

O(log k) updates beat full sorts when you only need extremes.

Approach

Use a priority queue for Top-K, scheduling, or Dijkstra-style extraction of minima.

  1. Pick min vs max heap polarity.
  2. Push/pop while maintaining size constraints.
  3. Read root as threshold/answer.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateHeap

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n)

Space: O(n)

Before coding, restate the problem, name the pattern (Heap), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #23 Merge k Sorted Lists as understood when the pattern clicks.