Sliding Window Maximum in java

Table of Contents

If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.

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


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

For eg :

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.


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:

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

That’s all about Sliding Window Maximum in java.


You may also like:

Related Posts

  • Maximum number of vowels in a Substring of given length
    18 June

    Maximum Number of Vowels in a Substring of Given Length

    Table of ContentsApproach – 1 Generate All Substrings Using substring() MethodApproach – 2 Using Sliding Window Method (Linear Time Solution) In this article, we will look at an interesting problem related to the Strings and [Sliding-Window Algorithm]( “Sliding-Window Algorithm”). The problem is : "Given a String we have to Find the Maximum Number of Vowel […]

  • Find first and last position of element in sorted array
    04 June

    Search for a range Leetcode – Find first and last position of element in sorted array

    Table of ContentsApproach 1 (Using Linear Search)Approach 2 (Using Modified Binary Search-Optimal) In this article, we will look into an interesting problem asked in Coding Interviews related to Searching Algorithms. The problem is: Given a Sorted Array, we need to find the first and last position of an element in Sorted array. This problem is […]

  • 30 April

    Convert Postfix to Infix in Java

    Learn about how to convert Postfix to Infix in java.

  • Prefix to postfix in java
    30 April

    Convert Prefix to Postfix in Java

    Learn about how to convert Prefix to Postfix in java.

  • Data structures in java
    16 April

    Data Structures in java

    Table of ContentsArray Declare and initialize array in javaAdvantages of arrayDisadvantages of array ExampleArray practice programsStackStack implementation using ArrayStack implementation using LinkedListImplementationPractice ProgramsQueueQueue implementation using arrayQueue implementation using LinkedListImplementationLinkedListImplementationLinkedList Practice ProgramsBinary treeImplementationBinary tree practice programsBinary Search treeImplementationBinary search tree Practice programsTrieImplementationHeapImplementationGraphImplementation Inbuild data structures in javaStringHashMapLinkedHashMapArrayListLinkedListHashSet In this post, we will see about various data […]

  • 29 November

    Top 100+ Java coding interview questions

    Table of ContentsStringQuestion 1 : How to reverse a String in java? Can you write a program without using any java inbuilt methods?Question 2 : Write a java program to check if two Strings are anagram in java?Question 3 : Write a program to check if String has all unique characters in java?Question 4 : […]

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.