Search⌘ K
AI Features

Merge K Sorted Lists

Explore how to merge k sorted singly linked lists into a single sorted list using k-way merge techniques. Understand the problem constraints and develop a solution that efficiently combines multiple sorted lists. This lesson equips you with the skills to handle linked list merging challenges common in coding interviews.

Statement

You are given an array, lists, containing k singly linked lists. Each of these linked lists is individually sorted in ascending order.

Your task is to merge all k linked lists into a single sorted linked list in ascending order and return the merged list.

Constraints:

  • k ==== lists.length

  • 00 \leq k 103\leq 10^3

  • 00 \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.

Examples

canvasAnimation-image
1 / 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Merge K Sorted Lists

1.

What is the output if the following array is given as input?

lists = [
               1 → 2 → 3 → NULL,
               12 → 56 → 200 → NULL,
               -10 → -2 → 5 → NULL
            ]

A.

1 → 2 → 3 → 12 → 56 → 200 → -10 → -2 → 5 → NULL

B.

1 → 2 → 3 → -10 → -2 → 5 → 12 → 56 → 200 → NULL

C.

-10 → -2 → 1 → 2 → 3 → 5 → 12 → 56 → 200 → NULL

D.

-10 → -2 → 5 → 1 → 2 → 3 → 12 → 56 → 200 → NULL


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

Java
usercode > Solution.java
// Definition for a Linked List node
// class ListNode {
// int val;
// ListNode next;
// // Constructor
// public ListNode(int val) {
// this.val = val;
// this.next = null;
// }
// }
import ds_v1.LinkedList.ListNode;
import java.util.*;
class Solution {
public static ListNode mergeKLists(ListNode[] lists) {
// Replace this placeholder return statement with your code
return null;
}
}
Merge K Sorted Lists