<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.</p>

<ul>
	<li>For examples, if <code>arr = [2,<u>3</u>,4]</code>, the median is <code>3</code>.</li>
	<li>For examples, if <code>arr = [1,<u>2,3</u>,4]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>
</ul>

<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. There is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>

<p>Return <em>the median array for each window in the original array</em>. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
<strong>Explanation:</strong> 
Window position                Median
---------------                -----
[<strong>1  3  -1</strong>] -3  5  3  6  7        1
 1 [<strong>3  -1  -3</strong>] 5  3  6  7       -1
 1  3 [<strong>-1  -3  5</strong>] 3  6  7       -1
 1  3  -1 [<strong>-3  5  3</strong>] 6  7        3
 1  3  -1  -3 [<strong>5  3  6</strong>] 7        5
 1  3  -1  -3  5 [<strong>3  6  7</strong>]       6
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3
<strong>Output:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

from heapq import heappush, heappop
from collections import defaultdict

class Solution:
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
        if not nums or k <= 0:
            return []

        first_half_max_heap = []  # Max heap (inverted values for max behavior)
        second_half_min_heap = []  # Min heap
        medians = []
        balance = 0  # +1 for each element in first_half, -1 for each in second_half
        outgoing_dict = defaultdict(int)

        def rebalance():
            nonlocal balance
            # Ensures that the heaps are balanced
            while balance > 1:
                heappush(second_half_min_heap, -heappop(first_half_max_heap))
                balance -= 2
            while balance < 0:
                heappush(first_half_max_heap, -heappop(second_half_min_heap))
                balance += 2

        def add_num(num):
            nonlocal balance
            if not first_half_max_heap or num <= -first_half_max_heap[0]:
                heappush(first_half_max_heap, -num)
                balance += 1
            else:
                heappush(second_half_min_heap, num)
                balance -= 1
            rebalance()

        def remove_num(num):
            nonlocal balance
            outgoing_dict[num] += 1
            if num <= -first_half_max_heap[0]:
                balance -= 1
            else:
                balance += 1
            rebalance()

        def clean_heaps():
            nonlocal balance
            while first_half_max_heap and outgoing_dict[-first_half_max_heap[0]] > 0:
                outgoing_dict[-first_half_max_heap[0]] -= 1
                heappop(first_half_max_heap)
            while second_half_min_heap and outgoing_dict[second_half_min_heap[0]] > 0:
                outgoing_dict[second_half_min_heap[0]] -= 1
                heappop(second_half_min_heap)

        for i in range(len(nums)):
            add_num(nums[i])
            
            if i >= k - 1:

                if i >= k:
                    remove_num(nums[i - k])
                    clean_heaps()

                # Calculate and append the median
                if k % 2 == 0:
                    medians.append((-first_half_max_heap[0] + second_half_min_heap[0]) / 2.0)
                else:
                    medians.append(float(-first_half_max_heap[0]))

        return medians

28778