Sliding Window Maximum in java

In this post, we will see about Sliding Window Maximum in java


Problem

Given an Array of integers and an Integer k, Find the maximum element of from all the contiguous subarrays of size K.

For eg :

💻 Awesome Tech Resources:
  • Looking for ⚒️ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events 🗓️ Calendar.️
Input : int[] arr = {2,6,-1,2,4,1,-6,5}
int k = 3
output : 6,6,4,4,4,5

for every subarray of size k, Print its maximum element.


Solution

Naive Approach :
The basic solution would be just generating all the contiguous subarrays of size k and looping over them for finding out the max in that current subarray.
Considering, for every spot we are basically taking next ‘k’ element and then we loop over those k elements, so the worst time complexity of this algorithm would be O(n*k).

Slightly Efficient Approach:

We can surely reduce the time taken in finding max for every subarray by using Segment tree.
We can Implement a segment tree for the given array, and we can get the max of every subarray with range query [i, i+k-1].

  • Total number of nodes in segment tree :
    The worst time complexity for constructing the segment tree would be O(n) because we know,
    (i) Leaf nodes of segment tree contains all the elements of the array.
    (ii) The number of nodes on last level is the number of nodes on all the upper levels.
  • Mathematically,
  1. Consider length of the array to be n, therefore, leaf nodes of the segment tree will be n.
  2. hence, the number of nodes on all the upper levels will be n-1.
  3. Total nodes on segment tree for an array of length n will be:
    Tn = leaf nodes + nodes on upper levels
          = n + n-1
          = 2n+1
  • Complexity Analysis

The construction of our segment tree involves calculation for every node only once, so worst time complexity of construction of segment tree will be O(2n+1) i.e O(n).
and result for range query of each subarray will be calculate in O(logk).
The query calculation will be done for all the ‘n-k+1’ subarrays of size k.
therefore overall time complexity for this algorithm will be O((n-k+1)*logk) i.e. O(nlogk).

Most Efficient Approach :

In this approach we use Deque which helps us finding the sliding window maximum in O(n).

  • A Deque is basically a queue which is open on both the ends for both enqueue and Deque, that is, you can add or remove element either from front or rear.

What we actually do to solve the problem is:

we keep the k elements of the subarrays in the reverse sorted order, We need not keep all the k elements though which we will see later in code.

  • Generate the Deque for the first k elements, keeping them sorted in reverse order so that the maximum element is at the front.
  • If the Deque is empty, add the element straightaway, else check if the incoming element is greater than the last element, if it is, keep popping the elements from last until the last element of the remaining Deque is greater than the incoming element.
  • We also need to remove the elements which belong to different subarray. i.e the indices in the Deque must be in the range, [i, i+k].

An element will only be removed on two conditions :
(i) If the upcoming element is greater than the element at rear, if it, it will keep on popping the element until there comes a larger element at rear of remaining dequeue because we need to keep the array sorted in the reverse order.
(ii) If the element belongs to any other subarray then there is no point in keeping it.

When you run above program, you will get below output:

8
2 6 -1 2 4 1 -6 5
arr[]: { 2 6 -1 2 4 1 -6 5 }
3
6 6 4 4 4 5

That’s all about Sliding Window Maximum in java.


import_contacts

You may also like:

Related Posts

  • 29 November

    Top 100+ Java coding interview questions

    I have been posting data structure and coding interview questions on various topics such as Array, Queue, Stack, Binary tree, LinkedList, String, Number, ArrayList, etc. So I am consolidating a list of java coding interview questions to create an index post. I will keep adding links to this post whenever I will add new java […]

  • 18 April

    Minimum Number of Jumps to reach last Index

    If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs. In this post, we will see how to find Minimum Number of Jumps to reach last Index. Problem Given an array A of positive integers possibly zeroes, every index indicating the maximum length of a […]

  • 28 March

    Sort an array of 0s, 1s and 2s

    If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs. In this post, we will see how to sort an array of 0s, 1s and 2s.We have already seen a post on sort 0s and 1s in an array. Problem Given an array containing zeroes, […]

  • 04 March

    Check if it is possible to reach end of given Array by Jumping

    If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs.   Problem Given an array with positive integers as elements indicating the maximum length of a jump which can be made from any position in the array. Check if it is possible to have […]

  • 17 February

    Check if Array Elements are Consecutive

    If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs. In this post, we will see how to check if array elements are consecutive. Problem Given an array, we need to check if array contains consecutive elements. For example: Input: array[] = {5, 3, 4, […]

  • 04 February

    LCA of a K-ary Tree in O(Sqrt(height))

    If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs. In this post, we will see about how to find Lowest Common Ancestor of a K-ary Tree in O(Sqrt(height)).We have already seen how to find LCA of n-ary tree in O(n) complexity. Problem Given a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.