K-Way Merge



John Rankin @ May 10, 2023

K-way merge is a coding interview pattern used to merge multiple sorted arrays or lists into a single sorted list efficiently. It is often used when dealing with large amounts of sorted data that cannot fit into memory at once.

Here's an example implementation of the K-way merge pattern:

import heapq

def k_way_merge(arrays):
    result = []
    min_heap = []

    # Initialize the min heap with the first element from each array
    for i, array in enumerate(arrays):
        if len(array) > 0:
            heapq.heappush(min_heap, (array[0], i, 0))

    while min_heap:
        val, array_index, element_index = heapq.heappop(min_heap)
        result.append(val)

        # Move to the next element in the same array
        if element_index + 1 < len(arrays[array_index]):
            heapq.heappush(min_heap, (arrays[array_index][element_index + 1], array_index, element_index + 1))

    return result

Now, let's look at a couple of example questions and their solutions using the K-way merge pattern:

Example 1: Merge K Sorted Lists
Given K sorted linked lists, merge them into a single sorted linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def merge_k_lists(lists):
    arrays = []
    
    # Convert linked lists into arrays
    for linked_list in lists:
        array = []
        current = linked_list
        while current:
            array.append(current.val)
            current = current.next
        arrays.append(array)
    
    # Use K-way merge to merge the arrays
    merged_array = k_way_merge(arrays)
    
    # Convert the merged array back into a linked list
    dummy = ListNode()
    current = dummy
    for val in merged_array:
        current.next = ListNode(val)
        current = current.next
    
    return dummy.next

Example 2: Merge K Sorted Arrays
Given K sorted arrays, merge them into a single sorted array.

def merge_k_arrays(arrays):
    return k_way_merge(arrays)

 

In both examples, we convert the given data structure (linked lists or arrays) into arrays, apply the K-way merge pattern, and then convert the merged result back into the desired data structure.

Note that the complexity of the K-way merge pattern is O(N log K), where N is the total number of elements across all arrays and K is the number of arrays. This is because we push and pop elements into the min heap, which has a maximum size of K.

 
 

 



 

 

 

Most Recent Posts


Bitwise XOR-exclusive OR

Read This
May 10, 2023

0-1 Knapsack

Read This
May 10, 2023

K-Way Merge

Read This
May 10, 2023

Subsets

Read This
May 10, 2023

Backtracking

Read This
May 10, 2023

Greedy Algorithm

Read This
May 10, 2023

Trie

Read This
May 10, 2023

Depth-First Search-DFS

Read This
May 10, 2023

Breadth-First Search-BFS

Read This
May 10, 2023

Binary Search Tree-BST

Read This
May 10, 2023

Top K Elements

Read This
May 10, 2023

Binary Search Pattern

Read This
May 10, 2023

Cyclic Sort pattern

Read This
May 10, 2023

Merge Intervals

Read This
May 10, 2023

Day 7 - DynamoDB - and Working with 2 Services - Lambda

Read This
August 25, 2018

Day 6 - Lambda - Creating an API

Read This
August 23, 2018

AWS - Day 5 - S3 - Simple Storage Service

Read This
August 22, 2018

AWS - Day 4 - AWS CLI Useful Scripts

Read This
August 21, 2018

AWS - Day 3 - Create Container from another container

Read This
August 20, 2018

Day 2 - Docker Intro

Read This
August 17, 2018

AWS - Day1 - Tutorial - Launching my first Docker Container

Read This
August 16, 2018

AWS - Day 1 - Signing up and testing out their tutorials

Read This
August 16, 2018

Dynamic Programming - Edit Distance

Read This
December 19, 2016

Dynamic Programming - Fibonacci

Read This
December 19, 2016