import heapq
def k_way_merge(sorted_lists):
heap = []
result = []
# Initialize heap with first element from each list along with list index and element index
for i, lst in enumerate(sorted_lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
while heap:
val, list_idx, element_idx = heapq.heappop(heap)
result.append(val)
# If next element exists in the same list, add it to the heap
if element_idx + 1 < len(sorted_lists[list_idx]):
next_val = sorted_lists[list_idx][element_idx + 1]
heapq.heappush(heap, (next_val, list_idx, element_idx + 1))
return result
# Example usage
lists = [[1,4,7], [2,5,8], [3,6,9]]
merged = k_way_merge(lists)
print(merged)