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

This approach uses a divide and conquer method to merge multiple sorted lists into a single sorted list. It initially pairs up the lists and merges each pair of lists. This merging of pairs produces (k2)(\frac{k}{2}) lists which, if merged produce (k4)(\frac{k}{4}) lists, and so on. This is repeated until we’re left with only one fully merged list. Merging a pair of lists uses two pointers, each pointing to a node in each list. If the node pointed by the first pointer has a value less than or equal to that pointed by the second one, it is added to the merged list. Otherwise, the value pointed by the second pointer is added. This is repeated until we have merged both lists into one. By merging each pair of lists, we end up with a single fully merged list at the end.

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