101 Logo
onenoughtone

Problem Statement

Dynamic Window Statistics

You're analyzing a time series dataset and need to calculate the median value for each window of consecutive data points.

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:

  • [2,3,4], the median is 3
  • [2,3], the median is (2 + 3) / 2 = 2.5

Given an array nums, 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.

Your task is to output the median array for each window in the original array.

Examples

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [1,-1,-1,3,5,6]
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

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1

Problem Breakdown

To solve this problem, we need to:

  1. The median of a window can be efficiently maintained using two heaps: a max heap for the smaller half and a min heap for the larger half
  2. As the window slides, we need to add a new element and remove an old element
  3. Removing elements from a heap is not straightforward, so we need to handle 'lazy deletion'
  4. We can also use a self-balancing binary search tree (like a multiset in C++) to maintain the sorted order of elements in the window
  5. The time complexity is dominated by the operations to maintain the sorted order of elements in the window
  6. For even-sized windows, the median is the average of the two middle elements
ProblemSolutionCode
101 Logo
onenoughtone