Advertisement
hoangreal

Merge K sorted lists of element (string, integers, ...)

Oct 20th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.45 KB | Source Code | 0 0
  1. """
  2. Merges k sorted lists of strings into one sorted list.
  3.  
  4. solve(["abc"]))           # -> ['a', 'b', 'c']
  5. solve(["abc", "def"]))    # -> ['a', 'b', 'c', 'd', 'e', 'f']
  6. solve(["abc", "abe"]))    # -> ['a', 'a', 'b', 'b', 'c', 'e']
  7. """
  8.  
  9. ### STEP 2 ###
  10. class Node:
  11.     def __init__(self, val, lst_idx, elem_idx):
  12.         self.val = val
  13.         self.lst = lst_idx
  14.         self.inx = elem_idx
  15.  
  16. class Min_Heap:
  17.     def __init__(self):
  18.         self.heap = []
  19.  
  20.     def add(self, val, lst_idx, elem_idx):
  21.         self.heap.append(Node(val, lst_idx, elem_idx))
  22.        
  23.         index = len(self.heap) - 1
  24.         while index > 0 and self.heap[index].val < self.heap[(index - 1) // 2].val:
  25.             parent = (index - 1) // 2
  26.             self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index]
  27.             index = parent
  28.  
  29.     def pop(self):
  30.         element = (self.heap[0].val, self.heap[0].lst, self.heap[0].inx)
  31.        
  32.         last_index = len(self.heap) - 1
  33.         self.heap[0] = self.heap[last_index]
  34.         self.heap.pop(-1)
  35.        
  36.         i = 0
  37.         while True:
  38.             left = 2 * i + 1; right = 2 * i + 2
  39.             smallest = i
  40.            
  41.             if left < len(self.heap) and self.heap[left].val < self.heap[smallest].val:
  42.                 smallest = left
  43.             if right < len(self.heap) and self.heap[right].val < self.heap[smallest].val:
  44.                 smallest = right
  45.             if smallest == i:
  46.                 break
  47.            
  48.             self.heap[i], self.heap[smallest] = self.heap[smallest], self.heap[i]
  49.             i = smallest
  50.  
  51.         return element
  52.  
  53.     def is_empty(self):
  54.         return len(self.heap) == 0
  55.  
  56. ### STEP 1 ###
  57. def solve_custom_heap(lists):
  58.     """
  59.    Time Complexity:  O(N log k) -- N = no. of chars; k = len('lists')
  60.    Space Complexity: O(N)       -- N = no. of chars
  61.    """
  62.     heap = Min_Heap()
  63.     result = []
  64.  
  65.     # Initialize the heap with the first element from each list
  66.     for i, lst in enumerate(lists):
  67.         if lst:
  68.             heap.add(lst[0], i, 0)
  69.  
  70.     # Extract the smallest item and add the next item from the same list to the heap
  71.     while not heap.is_empty():
  72.         val, list_idx, elem_idx = heap.pop()
  73.         result.append(val)
  74.         # If there is a next element in the same list, push it into the heap
  75.         if elem_idx + 1 < len(lists[list_idx]):
  76.             next_val = lists[list_idx][elem_idx + 1]
  77.             heap.add(next_val, list_idx, elem_idx + 1)
  78.  
  79.     return result
  80.  
  81. def solve_built_in(lists):
  82.     """
  83.    Time Complexity:  O(N log k) -- N = no. of chars; k = len('lists')
  84.    Space Complexity: O(N)       -- N = no. of chars
  85.    """
  86.     answers = []
  87.    
  88.     import heapq
  89.     heap = []
  90.  
  91.     # Initialize the heap with the first element from each list
  92.     for i, lst in enumerate(lists):
  93.         if lst:
  94.             # Push a tuple of (string value, list index, element index)
  95.             heapq.heappush(heap, (lst[0], i, 0))
  96.  
  97.     # Extract the smallest item and add the next item from the same list to the heap
  98.     while heap:
  99.        
  100.         val, list_idx, element_idx = heapq.heappop(heap)
  101.         answers.append(val)
  102.        
  103.         # If there is a next element in the same list, push it into the heap
  104.         if element_idx + 1 < len(lists[list_idx]):
  105.             next_val = lists[list_idx][element_idx + 1]
  106.             heapq.heappush(heap, (next_val, list_idx, element_idx + 1))
  107.  
  108.     return answers
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement