# Problem Understanding and visualize example

# Find the median in stream -> [mid1, mid2]

# Estimate time complexity

## N = 100k -> expect O(nlogn)

# Any contraints question

# Brute force: Sort and find middle

"""
- addNum: append to array time O(1), space O(1) for only new node.
- findMedian:
    - Sort an array: NlogN
    - Find the median from a[mid/2] + a[mid/2 + 1]
    - Time: O(NlogN)
    - Space: O(N), sortArray = sorted(arr) -> O(N)
"""

# Optimize Solution: Two Heap

"""
- Idea: you need find the max of half-min array, and the min of half-max array.

- addNum: to 2 min heap and max heap -> O(logN), space O(N)

- findMedian:

    - Get min-heap and max-heap: O(1)
    - Calculate: O(1)
    - Space: O(1)

"""

# Implementation

## Brute Force

"""
class MedianFinder:

    def __init__(self):
        # Step 1: Initialize an empty list to store all incoming numbers.
        # Time: O(1), Space: O(1)
        self.nums = []

    def addNum(self, num: int) -> None:
        # Step 2: Append the new number without sorting.
        # Time: O(1) amortized, Auxiliary space: O(1) amortized
        self.nums.append(num)

    def findMedian(self) -> float:
        # Step 3: Sort a copy so the original list remains unchanged.
        # Time: O(n log n), Auxiliary space: O(n)
        nums = sorted(self.nums)
        n = len(nums)

        # Step 4: If n is odd, return the single middle element.
        if n % 2 == 1:
            return float(nums[n // 2])

        # Step 5: If n is even, average the two middle elements.
        return (nums[n // 2 - 1] + nums[n // 2]) / 2
"""

## Optimize Solution: Two Heap

"""
import heapq

class MedianFinder:

    def __init__(self):
        # Step 1: Initialize two empty heaps.
        # small is a max heap simulated using negative values.
        # large is a normal min heap.
        # Time: O(1), Space: O(1)
        self.small = [] # max heap
        self.large = [] # min heap

    def addNum(self, num: int) -> None:
        # Step 2: Insert into the appropriate half.
        # small[0] represents the largest value in the lower half,
        # while large[0] represents the smallest value in the upper half.
        # Time: O(log n)
        if not self.small or num <= -self.small[0]:
            heapq.heappush(self.small, -num)
        else:
            heapq.heappush(self.large, num)

        # Step 3: Rebalance if the heap sizes differ by more than one.
        # Move the top element from the larger heap to the smaller heap.
        # Each heap push/pop takes O(log n).
        if len(self.small) > len(self.large) + 1:
            heapq.heappush(self.large, -heapq.heappop(self.small))

        elif len(self.large) > len(self.small) + 1:
            heapq.heappush(self.small, -heapq.heappop(self.large))

    def findMedian(self) -> float:
        # Step 4: Read the median directly from the heap tops.
        # Equal sizes: average the two middle values.
        if len(self.small) == len(self.large):
            return (-self.small[0] + self.large[0]) / 2

        # Unequal sizes: the larger heap contains the middle value.
        if len(self.small) > len(self.large):
            return float(-self.small[0])

        return float(self.large[0])
"""

import heapq

class MedianFinder:

    def __init__(self):
        # Step 1: Initialize two empty heaps.
        # small is a max heap simulated using negative values.
        # large is a normal min heap.
        # Time: O(1), Space: O(1)
        self.small = []
        self.large = []

    def addNum(self, num: int) -> None:
        # Step 2: Insert into the appropriate half.
        # small[0] represents the largest value in the lower half,
        # while large[0] represents the smallest value in the upper half.
        # Small must exists before Large -> due to we push to small first.
        # Time: O(log n)
        if not self.small or num <= -self.small[0]:
            heapq.heappush(self.small, -num)
        else:
            heapq.heappush(self.large, num)

        # Step 3: Rebalance if the heap sizes differ by more than one.
        # Move the top element from the larger heap to the smaller heap.
        # Each heap push/pop takes O(log n).
        if len(self.small) > len(self.large) + 1:
            heapq.heappush(self.large, -heapq.heappop(self.small))

        elif len(self.large) > len(self.small) + 1:
            heapq.heappush(self.small, -heapq.heappop(self.large))

    def findMedian(self) -> float:
        # Step 4: Read the median directly from the heap tops.
        # Equal sizes: average the two middle values.
        if len(self.small) == len(self.large):
            return (-self.small[0] + self.large[0]) / 2

        # Unequal sizes: the larger heap contains the middle value.
        if len(self.small) > len(self.large):
            return float(-self.small[0])

        return float(self.large[0])