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



class Solution:
    # # Keep a sorted interval
    # # Time: O(n * klogk) to O(n * k)
    # # Space: O(k)
    # def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
    #     import bisect

    #     sorted_nums = []
    #     medians = []
    #     for i in range(len(nums)):
    #         bisect.insort(sorted_nums, nums[i])

    #         if len(sorted_nums) > k:
    #             sorted_nums.pop(bisect.bisect(sorted_nums, nums[i - k]) - 1)

    #         if i >= k - 1:
    #             mid = k // 2
    #             if k % 2 == 1:
    #                 medians.append(sorted_nums[mid])
    #             else:
    #                 medians.append((sorted_nums[mid - 1] + sorted_nums[mid]) / 2)

    #     return medians

    # Two heaps using balance flag to maintain invariant
    # Invariant: len(small) >= len(large) by at most 1
    # Time: O(n * logk)
    # Space: O(n) hash table
    # def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
    #     import heapq
    #     from collections import Counter

    #     # initialize heaps making sure len(small) >= len(large)
    #     small, large = [], nums[:k]
    #     heapq.heapify(large)
    #     while len(small) < len(large):
    #         heapq.heappush(small, -heapq.heappop(large))

    #     to_remove = Counter()
        
    #     # insert first median value
    #     medians = [-small[0] if k & 1 else (-small[0] + large[0]) / 2]
        
    #     for i in range(k, len(nums)):
            
    #         # Handle the element leaving the window
    #         out_num = nums[i - k]
    #         to_remove[out_num] += 1
    #         balance = -1 if out_num <= -small[0] else 1

    #         # Determine which heap to insert new element
    #         if nums[i] <= -small[0]:
    #             heapq.heappush(small, -nums[i])
    #             balance += 1
    #         else:
    #             heapq.heappush(large, nums[i])
    #             balance -= 1
            
    #         # Fix the balance of the two heaps to maintain invariant
    #         if balance < 0:
    #             heapq.heappush(small, -heapq.heappop(large))
    #         if balance > 0:
    #             heapq.heappush(large, -heapq.heappop(small))

    #         # Pop any element that is not in the currect window
    #         while to_remove[-small[0]] > 0:
    #             to_remove[-heapq.heappop(small)] -= 1

    #         while large and to_remove[large[0]] > 0:
    #             to_remove[heapq.heappop(large)] -= 1

    #         # Get median
    #         if k & 1 == 0:
    #             medians.append((-small[0] + large[0]) / 2)
    #         else:
    #             medians.append(-small[0])

    #     return medians       


    # Two heaps using balance flag to maintain invariant
    # Invariant: len(small) >= len(large) by at most 1
    # Time: O(n * logk)
    # Space: O(n) hash table
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
        from sortedcontainers import SortedSet

        tset = SortedSet()
        medians = []

        for i in range(len(nums)):
            if i >= k:
                tset.discard((nums[i-k], i-k))
            
            tset.add((nums[i], i))

            if i >= k-1:
                if k & 1:
                    medians.append(tset[k//2][0])
                else:
                    medians.append((tset[(k-1)//2][0] + tset[k//2][0]) / 2)

        return medians

            




32515