"""Binary min-heap (priority queue).

Idea
----
A complete binary tree stored in a list: the children of index ``i`` live at
``2i + 1`` and ``2i + 2`` and its parent at ``(i - 1) // 2``. The heap rule
is "every parent <= its children", so the minimum is always at index 0.

* push: append at the end, then *sift up* while smaller than the parent.
* pop:  move the last element to the root, then *sift down* by swapping
  with the smaller child until the rule holds.

The standard library's ``heapq`` module implements the same idea on plain
lists; this class exists so you can see the moving parts.

Complexity
----------
push / pop: O(log n); peek: O(1); heapify from a list: O(n)
"""

from collections.abc import Iterable
from typing import Any


class MinHeap:
    def __init__(self, items: Iterable[Any] = ()) -> None:
        self._data = list(items)
        for i in range(len(self._data) // 2 - 1, -1, -1):
            self._sift_down(i)

    def push(self, item: Any) -> None:
        self._data.append(item)
        self._sift_up(len(self._data) - 1)

    def pop(self) -> Any:
        if not self._data:
            raise IndexError("pop from empty heap")
        data = self._data
        data[0], data[-1] = data[-1], data[0]
        smallest = data.pop()
        if data:
            self._sift_down(0)
        return smallest

    def peek(self) -> Any:
        if not self._data:
            raise IndexError("peek at empty heap")
        return self._data[0]

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

    def _sift_up(self, i: int) -> None:
        data = self._data
        while i > 0:
            parent = (i - 1) // 2
            if data[i] < data[parent]:
                data[i], data[parent] = data[parent], data[i]
                i = parent
            else:
                return

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