Blind 75
24 / 75Free practice

Merge K Sorted Lists

Hard · Linked lists

Jump to code

Merge k ascending singly linked lists into one ascending list. Inputs may contain empty lists.

Examples

Example 1

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

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

Example 2

lists = []

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.

Function contract

Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.

Need a hint?

Only the head of each remaining list can be the next smallest node.

Asked in real interviews

Candidates reported versions of Merge K Sorted Lists from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      1,
      4,
      5
    ],
    [
      1,
      3,
      4
    ],
    [
      2,
      6
    ]
  ]
]
Expected
[
  1,
  1,
  2,
  3,
  4,
  4,
  5,
  6
]
Case 2
Input
[
  []
]
Expected
[]
Case 3
Input
[
  [
    []
  ]
]
Expected
[]
Case 4
Input
[
  [
    [
      1,
      2,
      2
    ],
    [
      1,
      1,
      2
    ]
  ]
]
Expected
[
  1,
  1,
  1,
  2,
  2,
  2
]
Case 5
Input
[
  [
    [
      -1,
      0,
      1
    ],
    [],
    [
      2
    ]
  ]
]
Expected
[
  -1,
  0,
  1,
  2
]

Drafts are saved per language in this browser when storage is available.