Solution: Merge K Sorted Lists

Let's solve the Merge K Sorted Lists problem with the K-way Merge pattern.

Statement

Given an array of kk sorted linked lists, your task is to merge them into a single sorted linked list and return the head of this linked list.

Constraints:

  • k=k = lists.length
  • 0≤k≤1030 \leq k \leq 10^3
  • 0≤0 \leq lists[i].length ≤500\leq 500
  • −103≤-10^3 \leq lists[i][j] ≤103\leq 10^3
  • Each lists[i] is sorted in ascending order.
  • The sum of all lists[i].length will not exceed 10310^3.

Solution

Since our task involves multiple lists, we can use the divide and conquer technique, starting with pairing the lists and then merging each pair. We repeat this until all the given lists are merged. This way, after the first pairing, we’re left with k2\frac{k}{2} lists, then k4\frac{k}{4}, k8\frac{k}{8} and so on.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.