LeetCode 23. Merge k Sorted Lists— Graphically Explained Python3 Solution

 

Problem Description

Merge all the linked-lists into one sorted linked-list and return it.

Example:

Input: lists = [[1,1,5],[1,3,4],[2,6]]
Output: [1,1,1,2,3,4,5,6]
Explanation: The linked-lists are:
[
1->1->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->1->2->3->4->5->6

Solution

Obvious Solution

Best Solution (to me)

Image for post

To show it more clearer, let me put some twists (showing only the leftmost element of each list):

Image for post

You can see from above, for all current leftmost elements, “1” (doesn’t matter which “1”, so I just pick the one in the first list) is the smallest element. Although I haven’t looked into all other elements, I’m pretty sure it’s the smallest element of ALL elements. Why? The reason is, within current smallest elemements (of all lists), it’s the smallest: smallest among the smallest :).

So “1” will be picked up as current smallest element and its next element (if any) will become current like below right part:

Image for post

Then I can repeat the process until all elements are visited.

Additional Tips:

  1. Dummy head of linked list

Detailed illustration can be found within below Cheatsheet article (search “dummy” in it). I recommend reading it before checking following source code.

2. Heapq (priority queue)

Detailed illustration of heapq can be found in above Cheatsheet article (search “heapq” in it). I recommend reading it before continue reading.

The heapq is used in source code to achieve O(1) complexity to get smallest element out of a bunch elements. A detail to know for Python3 heaqp is: when I heappush a tuple, by default, tuple[0] will be used to compare with existing tuples’ tuple[0], if there is equal pair, tuple[1] will be used.

So below code may report “TypeError: ‘<’ not supported between instances of ‘ListNode’ and ‘ListNode'”, since (1,n1)[0] == (1,n2)[0] and Python3 will compare n1 and n2 but “<” operator may not be implemented in ListNode class.

import heapq
h = []
n1 = ListNode(1)
n2 = ListNode(1)
heapq.heappush(h, (1, n1))
heapq.heappush(h, (1, n2)) #TypeError: '<' not supported ...

To avoid that, I add a unique counter to the tuple like:

import heapq
h = []
n1 = ListNode(1)
n2 = ListNode(1)
cnt = 0
heapq.heappush(h, (1, cnt, n1))
cnt +=1
heapq.heappush(h, (1, cnt, n2))

Time & Space Complexity

Since I use a heap size of k, the space complexity is O(k).

Source Code





Comments

Popular posts from this blog

Leet Code 1060. Missing Element in Sorted Array — Explained Python3 Solution

Leet Code 84. Largest Rectangle in Histogram — Graphically Explained Python3 Solution