HardLinked ListDivide and ConquerHeap (Priority Queue)Merge Sort

Merge k Sorted Lists

LeetCode
1 approach, code in all languages

You are given an array of k linked lists, where each individual list is already sorted in ascending order by node value.

Merge every list into a single sorted linked list and return the head of that combined list. The result must preserve ascending order across all nodes drawn from every input list.

Some of the input lists may be empty, and the whole array itself may be empty, in which case the merged result is an empty list.

Example 1

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

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

The three sorted lists are 1->4->5, 1->3->4 and 2->6. Interleaving them in ascending order produces 1->1->2->3->4->4->5->6.

Example 2

Input: lists = []

Output: []

There are no lists to merge, so the result is the empty list.

Constraints

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • Each lists[i] is sorted in ascending order
  • The sum of lists[i].length will not exceed 10^4
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now