> For the complete documentation index, see [llms.txt](https://bhabs.gitbook.io/prepbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bhabs.gitbook.io/prepbook/coding/merge-k-sorted-arrays.md).

# Merge K sorted arrays

Merge 'k' sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

```
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
'''
heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, heap[0].
'''
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        # import heapq module
        import heapq

        h = [] # this list will define the heap using the heapq module in Python

        k = len(lists) # number of k sorted lists

        mergedList = [] # return this
        #================================================================================
        # base case
        #================================================================================
        if not k:
            return mergedList

        #================================================================================
        # Store the pointers to the next Node in an iterable list
        # This will help us to quickly come to the next Node in the correct kth list, after the smallest
        # element is popped from the heap.
        #================================================================================
        iterList = [None for i in xrange(k)]

        #================================================================================
        # Initially: Just buld a heap with the first elements from all k sorted lists
        #            Each heap element is a tuple of (element value, listIndex)
        #            The listIndex in the tuple will help us identify the which list number
        #            out of those k lists to go to after this tuple gets popped.
        #================================================================================
        for listIndex in xrange(k):
            list = lists[listIndex]
            if list:
                tup = tuple((list.val, listIndex))
                #print 'tup(start): ', tup
                heapq.heappush(h, tup)
                iterList[listIndex] = list.next # store the next pointer


        #================================================================================
        # Main task: 1. Pop the smallest tuple from the heap.
        #            2. Find the listIndex from that popped tuple
        #            3. Find the list Node from the pointer stored in the iterList for that listIndex
        #            4. Push that list node on to the heap
        #            5. The heapq will maintain the smallest element always at the top
        #================================================================================

        while h:
            elem = heapq.heappop(h)
            listIndex = elem[1]
            #print 'min elem: ', elem[0], ' listIndex = ', listIndex
            mergedList.append(elem[0])

            if iterList[listIndex] is not None:
                tup = tuple((iterList[listIndex].val, listIndex))
                #print 'tup: ', tup
                heapq.heappush(h, tup)
                iterList[listIndex] = iterList[listIndex].next

        #print 'merged List: ', mergedList
        return mergedList
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bhabs.gitbook.io/prepbook/coding/merge-k-sorted-arrays.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
