The problem stated on LeetCode is as follows:
Merge k 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
I am able to pass 129 out of 131 test cases but hit "time limit exceeded" on case 130. Below is my implementation.
Can someone spot the bottleneck? Any suggestions on improving time complexity?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# def print_lists(self, lists):
# idx = 0
# while idx < len(lists):
# ptr = lists[idx]
# _l = []
# while ptr is not None:
# _l.append(ptr.val)
# ptr = ptr.next
# idx += 1
# print(_l)
def min_idx(self, lists):
idx = 0
for i in range(len(lists)):
if lists[i] is None:
continue
elif lists[idx] is None:
idx = i
elif lists[i].val < lists[idx].val:
idx = i
return idx
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
head = tail = ListNode(-1)
while len(lists) > 0:
m_idx = self.min_idx(lists)
if lists[m_idx] is None:
return head.next
tail.next = lists[m_idx]
tail = tail.next
lists[m_idx] = lists[m_idx].next
if lists[m_idx] is None:
del lists[m_idx]
return head.next
I run into the "time limit exceeded" issue with our without using del. Test case 130 contains 10,000 LinkedLists.
del lists[m_idx], it will convert your algorithm into a quadratic one..heapq.merge()already implements this, but using it might be considered cheating so you may want to go a level deeper. docs.python.org/3/library/heapq.html#heapq.merge