"""Pattern 16: K-way merge.

Merging k sorted sequences: put the head of each into a min-heap, pop the
smallest, and push the next element from the same sequence. O(N log k) for N
total elements. Include an index in heap entries so ties never compare
uncomparable objects (like ListNodes).
"""

import heapq

from templates.structures import ListNode


def merge_sorted_lists(lists: list[list[int]]) -> list[int]:
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
    heapq.heapify(heap)
    out: list[int] = []
    while heap:
        value, i, j = heapq.heappop(heap)
        out.append(value)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return out


def merge_k_linked_lists(lists: list[ListNode | None]) -> ListNode | None:
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)
    dummy = tail = ListNode()
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


def kth_smallest_in_matrix(matrix: list[list[int]], k: int) -> int:
    """Rows are sorted: treat each row as a list and pop k times."""
    heap = [(row[0], r, 0) for r, row in enumerate(matrix)]
    heapq.heapify(heap)
    for _ in range(k - 1):
        _, r, c = heapq.heappop(heap)
        if c + 1 < len(matrix[r]):
            heapq.heappush(heap, (matrix[r][c + 1], r, c + 1))
    return heap[0][0]


def smallest_range(lists: list[list[int]]) -> list[int]:
    """Smallest [lo, hi] containing at least one number from each list."""
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists)]
    heapq.heapify(heap)
    current_max = max(lst[0] for lst in lists)
    best = [heap[0][0], current_max]
    while True:
        value, i, j = heapq.heappop(heap)
        if current_max - value < best[1] - best[0]:
            best = [value, current_max]
        if j + 1 == len(lists[i]):
            return best
        nxt = lists[i][j + 1]
        current_max = max(current_max, nxt)
        heapq.heappush(heap, (nxt, i, j + 1))
