# Sliding Window Median – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

The **median** 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.

- For examples, if
`arr = [2,`

, the median is__3__,4]`3`

. - For examples, if
`arr = [1,`

, the median is__2,3__,4]`(2 + 3) / 2 = 2.5`

.

You are given an integer array `nums`

and an integer `k`

. There is a sliding window of size `k`

which is moving from the very left of the array to the very right. You can only see the `k`

numbers in the window. Each time the sliding window moves right by one position.

Return *the median array for each window in the original array*. Answers within `10`

of the actual value will be accepted.^{-5}

**Example 1:**

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

**Example 2:**

Input:nums = [1,2,3,4,2,3,1,4,2], k = 3Output:[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]

**Constraints:**

`1 <= k <= nums.length <= 10`

^{5}`-2`

^{31}<= nums[i] <= 2^{31}- 1

# C++ Sliding Window Median LeetCode Solution

```
``````
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
multiset<int> window(nums.begin(), nums.begin() + k);
auto mid = next(window.begin(), k / 2);
vector<double> medians;
for (int i=k; ; i++) {
// Push the current median.
medians.push_back((double(*mid) + *prev(mid, 1 - k%2)) / 2);
// If all done, return.
if (i == nums.size())
return medians;
// Insert nums[i].
window.insert(nums[i]);
if (nums[i] < *mid)
mid--;
// Erase nums[i-k].
if (nums[i-k] <= *mid)
mid++;
window.erase(window.lower_bound(nums[i-k]));
}
}
```

# Java Sliding Window Median LeetCode Solution

```
``````
public double[] medianSlidingWindow(int[] nums, int k) {
Comparator<Integer> comparator = (a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : a - b;
TreeSet<Integer> left = new TreeSet<>(comparator.reversed());
TreeSet<Integer> right = new TreeSet<>(comparator);
Supplier<Double> median = (k % 2 == 0) ?
() -> ((double) nums[left.first()] + nums[right.first()]) / 2 :
() -> (double) nums[right.first()];
// balance lefts size and rights size (if not equal then right will be larger by one)
Runnable balance = () -> { while (left.size() > right.size()) right.add(left.pollFirst()); };
double[] result = new double[nums.length - k + 1];
for (int i = 0; i < k; i++) left.add(i);
balance.run(); result[0] = median.get();
for (int i = k, r = 1; i < nums.length; i++, r++) {
// remove tail of window from either left or right
if(!left.remove(i - k)) right.remove(i - k);
// add next num, this will always increase left size
right.add(i); left.add(right.pollFirst());
// rebalance left and right, then get median from them
balance.run(); result[r] = median.get();
}
return result;
}
```

# Python 3 Sliding Window Median LeetCode Solution

```
``````
def medianSlidingWindow(nums, k):
small, large = [], []
for i, x in enumerate(nums[:k]):
heapq.heappush(small, (-x,i))
for _ in range(k-(k>>1)):
move(small, large)
ans = [get_med(small, large, k)]
for i, x in enumerate(nums[k:]):
if x >= large[0][0]:
heapq.heappush(large, (x, i+k))
if nums[i] <= large[0][0]:
move(large, small)
else:
heapq.heappush(small, (-x, i+k))
if nums[i] >= large[0][0]:
move(small, large)
while small and small[0][1] <= i:
heapq.heappop(small)
while large and large[0][1] <= i:
heapq.heappop(large)
ans.append(get_med(small, large, k))
return ans
def move(h1, h2):
x, i = heapq.heappop(h1)
heapq.heappush(h2, (-x, i))
def get_med(h1, h2, k):
return h2[0][0] * 1. if k & 1 else (h2[0][0]-h1[0][0]) / 2.
```

Array-1180

String-562

Hash Table-412

Dynamic Programming-390

Math-368

Sorting-264

Greedy-257

Depth-First Search-256

Database-215

Breadth-First Search-200

Tree-195

Binary Search-191

Matrix-176

Binary Tree-160

Two Pointers-151

Bit Manipulation-140

Stack-133

Heap (Priority Queue)-117

Design-116

Graph-108

Simulation-103

Prefix Sum-96

Backtracking-92

Counting-86

Sliding Window-73

Linked List-69

Union Find-66

Ordered Set-48

Monotonic Stack-47

Recursion-43

Trie-41

Binary Search Tree-40

Divide and Conquer-40

Enumeration-39

Bitmask-37

Queue-33

Memoization-32

Topological Sort-31

Geometry-30

Segment Tree-27

Game Theory-24

Hash Function-24

Binary Indexed Tree-21

Interactive-18

Data Stream-17

String Matching-17

Rolling Hash-17

Shortest Path-16

Number Theory-16

Combinatorics-15

Randomized-12

Monotonic Queue-9

Iterator-9

Merge Sort-9

Concurrency-9

Doubly-Linked List-8

Brainteaser-8

Probability and Statistics-7

Quickselect-7

Bucket Sort-6

Suffix Array-6

Minimum Spanning Tree-5

Counting Sort-5

Shell-4

Line Sweep-4

Reservoir Sampling-4

Eulerian Circuit-3

Radix Sort-3

Strongly Connected Componen-t2

Rejection Sampling-2

Biconnected Component-1