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
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).
1FUNCTION mergeTwoLists(l1, l2):2 make a dummy start node; tail = dummy3 WHILE both l1 and l2 still have nodes:4 IF l1's value < l2's value: attach l1's node after tail; move l1 forward5 ELSE: attach l2's node after tail; move l2 forward6 tail = the node after tail7 END WHILE8 attach whichever list still has nodes after tail9 RETURN the node after dummy10END FUNCTION11FUNCTION 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 FOR16 RETURN head17END FUNCTION
← / → step · space play · Home restart