nathanwailes

Merge k sorted lists

Jun 10th, 2024
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. """
  2. """
  3. import heapq
  4.  
  5. def merge_k_sorted_lists(lists):
  6.     min_heap = []
  7.     for i, lst in enumerate(lists):
  8.         if lst:
  9.             heapq.heappush(min_heap, (lst[0], i, 0))
  10.    
  11.     merged_list = []
  12.     while min_heap:
  13.         val, list_idx, element_idx = heapq.heappop(min_heap)
  14.         merged_list.append(val)
  15.         if element_idx + 1 < len(lists[list_idx]):
  16.             next_tuple = (lists[list_idx][element_idx + 1], list_idx, element_idx + 1)
  17.             heapq.heappush(min_heap, next_tuple)
  18.    
  19.     return merged_list
  20.  
  21. # Example usage
  22. lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
  23. print(merge_k_sorted_lists(lists))  # Output: [1, 1, 2, 3, 4, 4, 5, 6]
  24.  
Advertisement
Add Comment
Please, Sign In to add comment