Back

Merge k Sorted Lists

hard

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.

Test Cases

Copy an input into the main harness and Run to verify
Input
lists = [[1,4,5],[1,3,4],[2,6]]
Expected Output
[1,1,2,3,4,4,5,6]

Explanation: Merging all lists gives one sorted list.

Input
lists = []
Expected Output
[]
Input
lists = [[]]
Expected Output
[]

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.

Hints

Hint 1 — click to reveal

You only ever need to compare the current heads of the k lists.

Hint 2 — click to reveal

A min-heap of heads gives you the next node in O(log k).

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.