Visualize

Pattern visualizer

Merge k Sorted Lists

Merging two sorted lists always produces another sorted list, so that result can be fed straight back into the same merge step as if it were just another input list — there's no need for a different algorithm once k grows past two. Fold the lists together one at a time: merge list1+list2, merge that sorted result with list3, and so on, each step reusing the same two-pointer comparison as merging two lists. Reach for it when combining more than two sorted sequences. Animated on: Pairwise merge of 3 sorted lists: [1,4,5] + [1,3,4] → [1,1,3,4,5], then merged with [2,6] → [1,1,2,3,4,5,6].

Linked List

step 1 / 15
1
[0]
4
[1]
5
[2]
1
[3]
3
[4]
4
[5]
2
[6]
6
[7]
line 14

3 sorted lists: list1=[1,4,5] at idx0-2, list2=[1,3,4] at idx3-5, list3=[2,6] at idx6-7. Pass 1: mergeTwoLists(list1, list2).

Pseudocode
1FUNCTION mergeTwoLists(l1, l2):
2 make a dummy start node; tail = dummy
3 WHILE both l1 and l2 still have nodes:
4 IF l1's value < l2's value: attach l1's node after tail; move l1 forward
5 ELSE: attach l2's node after tail; move l2 forward
6 tail = the node after tail
7 END WHILE
8 attach whichever list still has nodes after tail
9 RETURN the node after dummy
10END FUNCTION
11FUNCTION mergeKLists(lists):
12 head = lists[0]
13 FOR i from 1 up to the length of lists:
14 head = mergeTwoLists(head, lists[i])
15 END FOR
16 RETURN head
17END FUNCTION

← / → step · space play · Home restart

Where to practice Linked List