"""Blind 75, Heap section (3 problems; Merge K Sorted Lists lives in linked_list.py)."""
import heapq
from collections import Counter
from typing import List


def top_k_frequent(nums: List[int], k: int) -> List[int]:
    """LC 347. Bucket sort by frequency: index = count, so reading buckets from the top is O(n)."""
    buckets: List[List[int]] = [[] for _ in range(len(nums) + 1)]
    for value, count in Counter(nums).items():
        buckets[count].append(value)
    out: List[int] = []
    for bucket in reversed(buckets):
        for value in bucket:
            out.append(value)
            if len(out) == k:
                return out
    return out


class MedianFinder:
    """LC 295. Max-heap for the smaller half, min-heap for the larger half; keep sizes within one."""

    def __init__(self) -> None:
        self.low: List[int] = []   # max-heap via negated values
        self.high: List[int] = []  # min-heap

    def addNum(self, num: int) -> None:  # noqa: N802
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def findMedian(self) -> float:  # noqa: N802
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2
