Merge K Sorted Lists Solution for Amazon

Company: Amazon · Difficulty: Hard · Topics: Linked List, Divide and Conquer, Heap, Merge Sort

Problem Statement

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.

Examples

Example 1:

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

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

Explanation: Merging the three sorted lists gives us a sorted list.

Example 2:

Input: lists = []

Output: []

Explanation: No lists to merge.

Example 3:

Input: lists = [[]]

Output: []

Explanation: Empty list.

Example 4:

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

Output: [1,2,3,4,5,6,7,8,9]

Explanation: Merging three sorted lists.

Intuition

The key insight is to use a divide-and-conquer approach or a min-heap to efficiently merge multiple sorted lists. We can merge lists two at a time or use a heap to always pick the smallest element.

Approach

Approach 1: Divide and Conquer (Optimal)

1. Merge lists two at a time

2. Continue until only one list remains

3. This reduces the problem to merging two sorted lists repeatedly

Approach 2: Min Heap

1. Use a min heap to store the head of each list

2. Extract the minimum element and add it to result

3. Add the next element from the same list to heap

Approach 3: Brute Force

1. Collect all elements from all lists

2. Sort the combined list

3. Create a new linked list from sorted elements

Dry Run

Let's trace through Example 1: lists = [[1,4,5],[1,3,4],[2,6]]

Divide and Conquer Approach:

Min Heap Approach:

Solution

⚠️ Disclaimer: Don't jump directly to the solution, try it out yourself first. Only look at the solution after you've given it a good attempt.

Solution 1: Divide and Conquer (Optimal)

Time Complexity: O(n log k) - We merge log k times

Space Complexity: O(1) - Only need a few variables

Solution 2: Min Heap

Time Complexity: O(n log k) - Each element is inserted/extracted once

Space Complexity: O(k) - Heap size

Solution 3: Brute Force

Time Complexity: O(n log n) - Sort all elements

Space Complexity: O(n) - Store all elements

More Amazon coding questions