Updated on February 10, 2019
Problem
Merge sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Input
lists
- an array of linked list pointers
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
Approach
Normally when we think about merge sort, we usually only consider two linked lists. Given that the two linked lists are sorted, merging two linked lists is quite inexpensive -- we can achieve this in linear time complexity.
When we have linked lists, it's difficult to follow the above approach. Not only that, but it becomes difficult to keep track of the next linked list to traverse.
The most intuitive approach is to use pairs that houses two values: , where the value would be the number value of the linked list node, and the index is the integer value that represents which index this linked list resides in, inside lists
.
We now need a data structure that can effectively keep track of the smallest values. Since there are linked lists, we can use a binary heap to keep track of nodes, since we only need to keep track of at most nodes with distinct indices. (It does not make sense to have two nodes with the same linked list index, since ideally we only want to keep track of the minimum value so far from each distinct linked list.
Having nodes in our binary heap means that deletion will cost , and since we have nodes total, our merging process will cost . We take up only extra space, which is a very good benefit of using binary heaps.