—
Merge sorted lists with a heap
Tutor me on https://mlprep.iwase.dev/item/prog-ds-merge-sorted-lists/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-ds-merge-sorted-lists before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.Problem
Implement merge_sorted_lists(rows) where every inner list is sorted.
Return one sorted list. Use a heap containing at most one pending value
from each nonempty row, so total values across rows take
time.
Reveal answer or reference solution
Seed the heap with each row's first value and its row and column indices. Repeatedly pop the smallest entry, append its value, and push the next value from the same row. Row and column indices break value ties deterministically.
import heapq
def merge_sorted_lists(rows: list[list[int]]) -> list[int]:
heap: list[tuple[int, int, int]] = []
for row_index, row in enumerate(rows):
if row:
heapq.heappush(heap, (row[0], row_index, 0))
merged: list[int] = []
while heap:
value, row_index, column_index = heapq.heappop(heap)
merged.append(value)
next_column = column_index + 1
if next_column < len(rows[row_index]):
next_value = rows[row_index][next_column]
heapq.heappush(
heap, (next_value, row_index, next_column)
)
return mergedPublic tests
merge_sorted_lists([])→[]merge_sorted_lists([[], []])→[]merge_sorted_lists([[1, 4], [1, 3, 5], [2]])→[1, 1, 2, 3, 4, 5]merge_sorted_lists([[-3, 7], [-2, 0]])→[-3, -2, 0, 7]
Previous attempts
Loading attempts saved in this browser…