×

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in each window. This is done by advancing the window by a certain amount each step, allowing the data to be processed more efficiently than if it were processed all at once. Sliding window techniques are commonly used in data streaming, signal processing, and natural language processing. By replacing nested loops with a single loop, the Window Sliding Technique seeks to reduce the utilisation of nested loops and hence the complexity of computing.

Example

For example, consider streaming sensor data that record temperatures every minute. To calculate the maximum temperature for the last hour, we could store the temperatures for the last 60 minutes in a sliding window. As a new temperature value is received, the oldest value is dropped from the window, and the new value is added. The maximum temperature can then be calculated from the remaining values in the window.

Problem Statement

A sliding window problem is a type of algorithm in which an array or string is processed in order to find a subset of elements which meet certain conditions. The sliding window algorithm is often used to find a subset of elements that, when summed, equal a certain value. For example, let's say we have an array A which contains the following elements: [1,15,1,2,6,12,5,7]. We want to find a subset of elements in A which, when summed, equal 3. Using the sliding window algorithm, we can start by taking the first two elements, 1 and 15, and summing them. If the sum is 3, we have found our subset and can stop. If the sum is not 3, we can move the window to the next pair of elements, 15 and 1, and sum them. This process continues until the sum is equal to 3 or until we reach the end of the array.

Sliding Window Problem in Java
Sliding Window Problem in Java

Algorithm

  1. Initialize a window (a collection of elements) of size ‘k’.
  2. Iterate over the elements of the array, one element at a time.
  3. Add the current element to the window.
  4. Remove the oldest element from the window.
  5. Calculate the desired metric (for example, the sum of the elements) and record the result.
  6. Repeat steps 2-5 until no more elements are processed.
  7. Return the recorded results.

There are two types of Sliding window protocol

  1. Fixed-size window
  2. Variable size window

Fixed Size

The size of the required sub-array length is fixed. The size of the window should be only the given length. It cannot be altered.

Method

  • An array is given, we want to determine the highest sum that fits inside the subarray size of k.
  • First, we'll declare two variables: maxValue, which will save the highest value we can find, and currentWindowSum, which will record the window's current total.
  • Until the window size is bigger than or equal to our specified window size of k, we shall iterate through the array and add each value onto our currentWindowSum.
  • When this conditional is met, we will compare the maxValue to our currentWindowSum to determine which value is larger, and we will use that value as our new maxValue. Before iterating through our array and adding the next value, we will subtract the leftmost value.
  • Then, we give back our maxValue

File Name : SlidingWindow.java

import java.util.*;
class SlidingWindow {


	// Returns maximum sum in a subarray of size k.
	static int maxSum(int arr[], int n, int k)
	{
		// if n is greater than window size k
		if (n < k) {
			System.out.println("Invalid");
			return -1;
		}


		// find sum of first window elements of size k 
		int max_sum = 0;
		for (int i = 0; i < k; i++)
			max_sum += arr[i];


		// Subtract the first element from the previous window and add the last element from the current window to calculate the sums of the remaining windows.
		int window_sum = max_sum;
		for (int i = k; i < n; i++) {
			window_sum += arr[i] - arr[i - k];
			max_sum = Math.max(max_sum, window_sum);
		}


		return max_sum;
	}


	// Main section of the program where execution begins
	public static void main(String[] args)
	{
		Scanner sc =new Scanner(System.in);
	    System.out.println("Enter size of the array ");
	    // storing the size of the array into the integer variable n
	    int n=sc.nextInt();
	    System.out.println("enter array elements ");
	    // storing array values into the array
	    int a[]=new int[n];
	    for(int i=0;i<n;i++)
	    {
	        a[i] = sc.nextInt();
	    }
	    // enter the size of the window 
	    System.out.println("Enter the size of the window");
		int k = sc.nextInt();
		// finding the length of the array 
		int l = a.length;
		// calling the function and printing the result
		System.out.println("The maximum subarray of size "+k+" is ");
		System.out.println(maxSum(a, l, k));
	}
}

Output

Enter size of the array 
10
enter array elements 
1 3 5 24 52 1 24 3 2 6
Enter the size of the window
3
The maximum subarray of size 3 is 
81

Variable Size

The window size can be altered in variable-size sliding windows based on the requirement.

Method

  • This method is based on the minimum size subarray sum issue and applies to the variable window length example. We shall seek the smallest subarray that adds up to the desired value for this implementation.
  • Executing a problem with a variable window size is trickier since we need to keep track of where our window starts and finishes with more variables. We'll first declare these four variables:
VariableRequirement
minWindowSizeWhen we decide the smallest window size, we return this value. We must begin with a value that is much higher than our intended result.
currentWindowSumminimum window size will be compared to the current window size.
windowStartTo determine the lowest value of our window,where our window begins.
windowEndTo know the final minimum window value, we must always keep track of our window end.

Problem Statement

Find the index of 0 to be replaced with 1 in a binary array to obtain the longest possible continuous series of ones.

Take the array 0, 0, 1, 0, 1, 1, 1, 0, 1 as an illustration. To obtain a continuous sequence of length 6 that contains only 1s, the index that needs to be substituted is 8.

Method

Maintaining a window with a maximum of one zero at any given time while adding items from the right until the window becomes unstable is the goal. If there are two or more zeros in the window, it becomes unstable. If the window gets shaky, take away the elements on its left until it stabilises again. Update the index of 0 to be replaced if the window is stable and the current window length is greater than the largest window yet discovered.

File Name: SlidingWindow2.java

// importing the required packages
import java.util.*;
class SlidingWindow2
{
    //static declaration of the function to find the position of the index of the array
    public static int findIndexofZero(int[] A)
    {
        // declaration of the integer variables 
        int l = 0;      
        int c = 0;    
        int max_count = 0;  
 
        int ans = -1;         
        int prev_zero_index = -1;  
 
        for (int j = 0; j < A.length; j++)
        {
            
            if (A[j] == 0)
            {
                prev_zero_index = j;
                c++;
            }
 
        // the window becomes unstable if the total number of zeros in it becomes2
            if (c == 2)
            {
                // remove elements from the window's left side till we found a zero
                while (A[l] != 0) {
                    l++;
                }
 
                // remove the leftmost 0 so that window becomes stable again
                l++;
 
                // decrement count as 0 is removed
                c = 1;
            }
 
 
            if (j- l + 1 > max_count)
            {
                max_count = j - l + 1;
                ans = prev_zero_index;
            }
        }
 
        return ans;
    }
    // Main section of the program where execution begins
    public static void main (String[] args)
    {
        // creating object for scanner class
       Scanner sc =new Scanner(System.in);
       // enter the size of the array
	    System.out.println("Enter size of the array ");
	    // storing the size of the array into the integer variable n
	    int n=sc.nextInt();
	  // enter binary array elements
	    System.out.println("enter array elements ");
	    // storing array values into the array
	    int a[]=new int[n];
	    for(int i=0;i<n;i++)
	    {
	        a[i] = sc.nextInt();
	    }
	    // calling the function 
		System.out.println("The maximim index is");
	    System.out.println(findIndexofZero(a));


    }
}

Output

Enter size of the array 
7
enter array elements 
1 0 1 1 0 1 1
The maximum index is
4

Time Complexity

The above approach has an O(n) time complexity and uses no additional storage, where n is the length of the given sequence.


Related Topics

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.