for iit in enumerate sorted_arrays_iters )first_element next(it noneif first_element is not noneheapq heappush (min_heap first_element )result [while min_heap smallest_entry smallest_array_i heapq heappop min_heap smallest_array_iter sorted_arrays_iters smallest_array_i result append smallest_entry next_element nextsmallest_array_iter noneif next_element is not noneheapq heappush (min_heap next_element smallest_array_i )return result pythonic solution uses the heapq merge (method which takes multiple inputs def merge_sorted_arrays_pythonic sorted_arrays )return listheapq merge (sorted_arrays )let be the number of input sequences then there are no more than elements in the min-heap both extract-min and insert take (log ktime hencewe can do the merge in ( log ktime the space complexity is (kbeyond the space needed to write the final result in particularif the data comes from files and is written to fileinstead of arrayswe would need only (kadditional storage alternativelywe could recursively merge the filestwo at time using the merge step from merge sort we would go from to / then / etc files there would be log stagesand each has time complexity ( )so the time complexity is the same as that of the heap-based approachi ( log kthe space complexity of any reasonable implementation of merge sort would end up being ( )which is considerably worse than the heap based approach when