"""Week 11: Binary heaps and priority queues, built from scratch."""
from __future__ import annotations

import heapq
from typing import Iterable, List


class MinHeap:
    """Array-backed binary heap: children of i are 2i+1 and 2i+2, parent is (i-1)//2."""

    def __init__(self, values: Iterable = ()):
        self._a: List = list(values)
        for i in range(len(self._a) // 2 - 1, -1, -1):  # O(n) bottom-up heapify
            self._sift_down(i)

    def __len__(self) -> int:
        return len(self._a)

    def push(self, x) -> None:
        self._a.append(x)
        self._sift_up(len(self._a) - 1)

    def peek(self):
        if not self._a:
            raise IndexError("peek at empty heap")
        return self._a[0]

    def pop(self):
        if not self._a:
            raise IndexError("pop from empty heap")
        last = self._a.pop()
        if not self._a:
            return last
        top, self._a[0] = self._a[0], last
        self._sift_down(0)
        return top

    def _sift_up(self, i: int) -> None:
        a = self._a
        while i > 0:
            parent = (i - 1) // 2
            if a[i] >= a[parent]:
                break
            a[i], a[parent] = a[parent], a[i]
            i = parent

    def _sift_down(self, i: int) -> None:
        a, n = self._a, len(self._a)
        while True:
            smallest = i
            for child in (2 * i + 1, 2 * i + 2):
                if child < n and a[child] < a[smallest]:
                    smallest = child
            if smallest == i:
                return
            a[i], a[smallest] = a[smallest], a[i]
            i = smallest


def heap_sort(values: Iterable) -> List:
    heap = MinHeap(values)
    return [heap.pop() for _ in range(len(heap))]


def k_largest(values: Iterable, k: int) -> List:
    """Size-k min-heap: O(n log k). Returned in descending order."""
    heap: List = []
    for x in values:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)
    return sorted(heap, reverse=True)


def merge_sorted_lists(lists: List[List]) -> List:
    """k-way merge with (value, list index, element index) tuples."""
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
    heapq.heapify(heap)
    out = []
    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


class RunningMedian:
    def __init__(self):
        self._low: List = []   # max-heap via negation
        self._high: List = []  # min-heap

    def add(self, x) -> None:
        heapq.heappush(self._low, -x)
        heapq.heappush(self._high, -heapq.heappop(self._low))
        if len(self._high) > len(self._low):
            heapq.heappush(self._low, -heapq.heappop(self._high))

    def median(self) -> float:
        if not self._low:
            raise IndexError("no values yet")
        if len(self._low) > len(self._high):
            return float(-self._low[0])
        return (-self._low[0] + self._high[0]) / 2
