DIY: Sliding Window Median

Solve the interview question "Sliding Window Median" in this lesson.

Problem statement

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. We 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 10510^{-5} of the actual value will be accepted.

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 = [1,2,3], the median is 2.

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

Constraints:

  • 1 <= k <= nums.length <= 105
  • 231-2^{31} <= nums[i] <= 2312^{31} - 1

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.