InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Merge k Sorted Lists

hard Original ↗ 00:00

Problem

You are given an array of k linked lists, each already sorted in ascending order. Combine all of them into a single sorted linked list and return its head.

Some of the k lists may be empty, and the array itself may be empty. Let N be the total number of nodes across all lists; performance is measured against N. Merging two sorted lists is straightforward; the challenge is merging k of them efficiently.

Examples

  • Input: lists = [[1, 4, 5], [1, 3, 4], [2, 6]] → Output: [1, 1, 2, 3, 4, 4, 5, 6] All eight nodes merged into one ascending list.
  • Input: lists = [] → Output: [] No input lists, so the result is empty.
  • Input: lists = [[], [0]] → Output: [0] Empty lists must be handled without error.

Constraints

  • k is in [0, 10^4], each list has up to 500 nodes, total N up to about 5 * 10^5.
  • -10^4 <= Node.val <= 10^4; each input list is sorted ascending.
  • With k up to 10^4, an O(N * k) approach (scanning all k heads for every output node, or merging lists into the result one at a time) is too slow. The target is O(N log k).

Think about it first

Hint 1 At every step, the next output node is the smallest among the current heads of the k lists. How do you repeatedly extract the minimum of k changing candidates faster than scanning all k each time?
Hint 2 A min-heap of size k gives you the smallest head in O(log k). Pop a node, append it to the output, and push that node's successor — every node enters and leaves the heap exactly once.
Hint 3 Alternative with the same O(N log k) bound and O(1) heap-free space: divide and conquer. Merge lists in pairs (1 with 2, 3 with 4, …), halving the count each round; after log k rounds one list remains, and each round touches every node once.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug