Monday, February 28, 2011

WAP to Find Maximum in Sliding Window of size W in an Unsorted Array or Integers.

A long array A[] is given to you. There is a sliding window of size w which is moving from the very left of the array to the very right. You can only see the w numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and w is 3.

Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
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 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7


Input: A long array A[], and a window width w
Output: An array B[], B[i] is the maximum value of from A[i] to A[i+w-1]
Requirement: Find a good optimal way to get B[i]

Solution: It Can Solved By Two Ways in This Question Data Structure Plays Important Role

The obvious solution with run time complexity of O(nw) is which is not efficient enough. Every time the window is moved, we have to search for the maximum from w elements in the window. where w is size of window & n is size of array

1st Method(Naive Approach)

Data Structure Used : Array
Algorithm: A.for all i=0 to n-w+1 (we should have at-least w elements in window)
B.for all j=i to i+w (keep incrementing windows size form left to right)
C find maximum inn each window & print it or put in array (Auxiliary)

#include

void printMaxInSlidingWindows(int a[],int n,int w)
{

int max=0;
int i=0,j=0;

for (i = 0; i {
max=a[i];

for (j=i; j {
if (a[j]>max)
{
max=a[j];

}



}
printf( " %d ", max);
}

}

int main()
{
int a[]={1,3,-1,-3,5,3,6,7};
printMaxInSlidingWindows(a,8,3);
}

TC O(nw)
SC O(1)
Run Here http://ideone.com/7o3Ta


2nd Method

Data Structure Used: Queue(More Efficient)
Algorithm Provided By Aakash (A Techie Who Run Blog on Coding,DS,Algorithms)

We need a data structure where we can store the candidates for maximum value in the window and discard the element, which are outside the boundary of window. For this, we need a data structure in which we can edit at both the ends, front and back. Deque is a perfect candidate for this problem.

We are trying to find a way in which, we need not search for maximum element among all in the window. We will make sure that the largest element in the window would always appear in the front of the queue.
While traversing the array in forward direction if we find a window where element A[i] > A[j] and i > j, we can surely say that A[j], will not be the maximum element for this and succeeding windows. So there is no need of storing j in the queue and we can discard A[j] forever.
For example, if the current queue has the elements: [4 13 9], and a new element in the window has the element 15. Now, we can empty the queue without considering elements 4, 13, and 9, and insert only element 15 into the queue.

Every time, we move to a new window, we will be getting a new element and leave an old element. We should take care of:
Popping elements outside the window from queue front.
Popping elements that are less than new element from the queue.
Push new element in the queue as per above discussion.

Note:Optimization Done In Done so that we can Find The Maximum of Each Window in O(1)

Here Is Tunning Code

import java.util.*;

class Maximumin_SlidingWindow
{

public static void main(String ar[])
{

Integer a[]=new Integer[]{1,3,-1,-3,5,3,6,7};
int w=3,i=0;
int size=a.length;
Integer b[]=new Integer[size-w+1];

maxSlidingWindow(a,size,w,b);

for(i=0;i System.out.println(b[i]);

}

static void maxSlidingWindow(Integer A[], int n, int w, Integer B[])
{
Integer ar[]=new Integer[1];
DequeQ=ar[0];

//Initilize deque Q for first window
for (int i = 0; i < w; i++)
{
while (!Q.isEmpty() && A[i] >= A[Q.peekLast()])
Q.pollLast();
Q.offerLast(i);
}

for (int i = w; i < n; i++)
{
B[i-w] = A[Q.peekFirst()];

//update Q for new window
while (!Q.isEmpty() && A[i] >= A[Q.peekLast()])
Q.pollLast();

//Pop older element outside window from Q
while (!Q.isEmpty() && Q.peekFirst() <= i-w)
Q.pollFirst();

//Insert current element in Q
Q.offerLast(i);
}
B[n-w] = A[Q.peekFirst()];
}

}

TC O(n)n Since Eacj Array Element is Inserted & deleted At-Most Once
SC O(1)
Run Here http://ideone.com/KLIpO
http://ideone.com/TftYg

5 comments :

Gaurav said...

Check your solution for the test case
{5,3,-1,-3} and window size 3.

according to your solution :
1st window -> max = 5
2nd window -> max < -3 is false. so, max = 5. which is wrong.

Unknown said...

@gauurav Thanks for Pointing out it. i have updates the solution that will cover all test cases , i have also provide the new optimized solution with dequeue data structure that will work efficiently for all arrays or length n & windows of size k...

thoughts_anshul said...
This comment has been removed by the author.
thoughts_anshul said...

Why cant we implement Window as a heap tree?
with entries as Tuple(positionInTheSeq, Value)
Heap will be ordered as per the Value.

So complexity getting Max is O(1)

and whenever window is changed we need to find Tuple(positionInTheSeq, Value) with least positionInTheSeq and deleting + adding a new entry, Will take O(log W )time.

Unknown said...

@anshul , Absolutely Correct,Keep it Up :) , I also had similar approach in mind , might be forgot to post here , Will try to provide code asap. for the same


Cheers !!!
Shashank