<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>

import heapq
from collections import defaultdict
from typing import List
import math

class Solution:
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
        top_heap = [] # or min heap 
        bottom_heap = [-x for x in nums[:k]] # or max heap
        heapq.heapify(bottom_heap)
        to_remove = defaultdict(int)
        result = []

        # initial state is bottom heap has k elements
        # put half in top heap (if odd extra element goes to bottom)
        for i in range(k//2):
            heapq.heappush(top_heap, -heapq.heappop(bottom_heap))
        
        # predefine this
        if k % 2:
            get_median = lambda: -bottom_heap[0]
        else:
            get_median = lambda: (-bottom_heap[0] + top_heap[0]) / 2

        median = get_median()
        result.append(median)
        
        X = len(nums) if k == 1 else int(k/math.log2(k))

        for i in range(k, len(nums)):
            new_element = nums[i]
            removed_element = nums[i - k]
            # at every step we remove one element and get a new one
            # the only cases we care about are drop bottom/gain top and drop top/gain bottom
            # let size_delta track the size difference
            rebalance_direction = -1 if removed_element <= median else 1

            # lazy delete - keep elements to be deleted in a hashmap
            # to_remove[x] = 0 means x has not been marked for deletion
            # to_remove[x] = N means N occurrences of X have been marked for deletion, this is done to
            #   account for repeating elements
            to_remove[removed_element] += 1

            # add new element
            if new_element <= median:
                rebalance_direction += 1
                heapq.heappush(bottom_heap, -new_element)
            else:
                rebalance_direction -= 1
                heapq.heappush(top_heap, new_element)
            
            # rebalance heaps
            if rebalance_direction < 0:
                heapq.heappush(bottom_heap, -heapq.heappop(top_heap))
            elif rebalance_direction > 0:
                heapq.heappush(top_heap, -heapq.heappop(bottom_heap))

            # remove "deleted" elements
            # we only care if these are at the top of the heaps because then we get wrong answers
            # as long as the top of the heap is an element inside the window, we get the correct answer
            # for each heap the root r is the max/min of the respective set (both including/excluding the "deleted" items),
            # and we have K//2 (+1) items from the window in each heap
            while bottom_heap and to_remove[-bottom_heap[0]] > 0:
                to_remove[-bottom_heap[0]] -= 1
                heapq.heappop(bottom_heap)
            
            while top_heap and to_remove[top_heap[0]] > 0:
                to_remove[top_heap[0]] -= 1
                heapq.heappop(top_heap)

            median = get_median()
            result.append(median)

            if i % X == 0:
                new_bottom_heap = []
                for x in bottom_heap:
                    if to_remove[-x] > 0:
                        to_remove[-x] -= 1
                    else:
                        new_bottom_heap.append(x)
                bottom_heap = new_bottom_heap
                heapq.heapify(bottom_heap)
                
                # Clean up top_heap
                new_top_heap = []
                for x in top_heap:
                    if to_remove[x] > 0:
                        to_remove[x] -= 1
                    else:
                        new_top_heap.append(x)
                top_heap = new_top_heap
                heapq.heapify(top_heap)

                while len(bottom_heap) > len(top_heap) + 1:
                    heapq.heappush(top_heap, -heapq.heappop(bottom_heap))
                while len(top_heap) > len(bottom_heap):
                    heapq.heappush(bottom_heap, -heapq.heappop(top_heap))
        
        return result

32946