Median of sliding window in an array

• Difficulty Level : Expert
• Last Updated : 13 Jan, 2020

Given an array of integer arr[] and an integer k, the task is to find the median of each window of size k starting from the left and moving towards the right by one position each time.

Examples:

Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, k = 3
Output: 5 8 8 3 3 3

Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, k = 4
Output: 6.5 6.5 5.5 3.0 2.5

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Create a pair class to hold the items and their index. It also implements the comparable interface so that compareTo() method will be invoked by the Treeset to find the nodes. Note that the two pairs are equal only when their indices are equal. This is important since a window can contain duplicates and we may end up deleting multiple items in single remove() call if we only check for the value.

The idea is to maintain two sorted sets (minSet and maxSet) of Pair objects of length (k / 2) and (k / 2) + 1 depending on whether k is even or odd, minSet will always contain the first set of numbers (smaller) of window k and maxSet will contain the second set of numbers (larger).

As we move our window, we will remove elements from either of the sets (log n) and add a new element (log n) maintaining the minSet and maxSet rule specified above.

Below is the implementation of the above approach: