Sliding Window Median - Problem
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 example, if arr = [2, 3, 4], the median is 3.
For example, if arr = [1, 2, 3, 4], the median is (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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,-1,-3,5,3,6,7], k = 3
›
Output:
[1.0,-1.0,-1.0,3.0,5.0,6.0]
💡 Note:
Window [1,3,-1] → sorted [-1,1,3] → median 1.0. Window [3,-1,-3] → sorted [-3,-1,3] → median -1.0. Continue for all windows.
Example 2 — Even Window Size
$
Input:
nums = [1,2,3,4], k = 2
›
Output:
[1.5,2.5,3.5]
💡 Note:
Window [1,2] → median (1+2)/2 = 1.5. Window [2,3] → median (2+3)/2 = 2.5. Window [3,4] → median (3+4)/2 = 3.5.
Example 3 — Single Element Window
$
Input:
nums = [1,4,2,3], k = 1
›
Output:
[1.0,4.0,2.0,3.0]
💡 Note:
Each window contains one element, so median equals that element: 1.0, 4.0, 2.0, 3.0.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
- -231 ≤ nums[i] ≤ 231 - 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code