Showing posts with label Sliding Window. Show all posts
Showing posts with label Sliding Window. Show all posts

Variable Size Sliding Window Algorithm.

Sliding Window is an efficient approach to solve problems involving contiguous subarrays. It can be used to find the maximum or minimum sum of a contiguous subarray of size k. This approach involves maintaining a "window" that moves from the left to the right of the array, keeping track of the sum of the elements within the window.

Dynamic Sliding Window Algorithm

Variable Size Sliding Window.

The Variable Size Sliding Window Algorithm, also known as Dynamic Sliding Window, is a technique used for efficiently processing arrays or lists to avoid unnecessary re-computation. Unlike the Fixed Size Sliding Window, where the window size remains constant, the Variable Size Sliding Window allows the window to dynamically adjust its size based on certain conditions.


Approach of Variable Size Sliding Window:

In this approach, we use two pointers left and right to define the window size. We move our right pointer to expand the window size until a certain condition is violated. Similarly, we move our left pointer to shrink the size of the window to the desired condition. Each time we either store a result or perform some computation whenever the size of the window is changed. We repeat these steps until the right pointer reaches the end of the array. 

Let's understand the working of the Variable Size Sliding Window Algorithm with an example problem.

Example to Illustrate the Dynamic Sliding Window Technique. 

Problem: Given an array of positive integer nums and a positive integer target, find the minimum length of a contiguous subarray whose sum is greater than or equal to the target. If no such subarray exists, return 0.

Example:
Input: num[] = {2, 3, 1, 2, 4, 3} target = 7
Output: 2

Explanation: The subarray [4,3] has the minimum length 
among the contiguous subarrays whose sum is greater than or equal to 7.

There are multiple approaches to solving this problem but here we will focus on the sliding window approach.

Algorithm:

Below are the steps to follow to solve this problem:

Step 1: We initialize a variable, 'minLen', to hold the minimum length of the contiguous subarray found so far. We also initialize a variable, 'sum', to keep track of the sum of the elements in the current window.

Step 2: We iterate over the input array, using a for loop to iterate through each element. For each element, we add its value to the 'sum' variable.

Step 3: Inside the for loop, we check if the 'sum' is greater than or equal to the target. If it is, we update the 'minLen' variable to be the minimum of its current value and the current window's length (calculated using the 'right' pointer).

Step 4: After updating the 'minLen' variable, we slide the window to the right by subtracting the first element of the current window from the 'sum' variable. This involves incrementing the 'left' pointer by 1.

Step 5: We repeat steps 3-4 until the 'right' pointer reaches the end of the input array.

Step 6: Finally, we return the value of the 'minLen' variable, which represents the minimum length of the contiguous subarray whose sum is greater than or equal to the target.

Below is the code implementation of the Variable size Sliding Window problem.

C++ Code:
// C++ code implementation of finding the minimum length 
//of the subarray for given sum
#include <iostream>
#include <vector>
#include <climits> 
using namespace std;
int minSubarrayLen(int target, vector<int>& nums) {
    int n = nums.size();
    int left = 0, right = 0;
    int minLen = INT_MAX;
    int sum = 0;

    while (right < n) {
        sum += nums[right];

        while (sum >= target) {
            minLen = min(minLen, right - left + 1);
            sum -= nums[left];
            left++;
        }

        right++;
    }

    return (minLen == INT_MAX) ? 0 : minLen;
}

int main() {
    vector<int> nums = {2, 3, 1, 2, 4, 3};
    int target = 7;
    cout << minSubarrayLen(target, nums) << endl; 
    return 0;
}
Output:
2

Java Code:
// Java code to find minimum length subarray 
// for the given target 
public class VariableSizeSlidingWindow {

    public static int minSubArrayLen(int target, int[] nums) {
        int left = 0, right = 0, sum = 0;
        int minLength = Integer.MAX_VALUE;

        while (right < nums.length) {
            sum += nums[right];

            while (sum >= target) {
                minLength = Math.min(minLength, right - left + 1);
                sum -= nums[left];
                left++;
            }

            right++;
        }

        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};
        int target = 7;

        int result = minSubArrayLen(target, nums);

        System.out.println("Minimum Length: " + result);
    }
}
Output:
Minimum Length: 2
  • Time Complexity: The time complexity is O(n), where n is the length of the input array. This is because each element in the array is processed exactly once. 
  • Space Complexity: The space complexity is O(1), as we only use a constant amount of space to store the necessary variables.

Program to Count Subarrays with K Odd Numbers.

Given an integer array containing n elements and an integer value k, we need to write a program to count the number of continuous subarrays in the given array that contain k number of odd numbers. 

Example:
Input: arr[] = {3, 1, 2, 1, 1}, k = 3
Output: 2
Explanation:
Subarrays with 3 odd numbers are {3, 1, 2, 1} and {1, 2, 1, 1}. 

Input: arr[] = {2, 1, 9, 3, 1}, k = 2
Output: 4
Explanation:
Subarrays with 2 odd numbers are 
{1, 9} {9, 3} {3, 1} {2, 1, 9} 

This problem can be solved by multiple approaches, let's discuss each of them one by one with efficiency.

Approach 1: Brute Force.

The brute force approach involves considering all possible subarrays of the given array and checking each subarray to see if it contains exactly k odd numbers.

Below is the C++ code implementation for this approach.
//C++ code to Count Subarrays with K Odd Numbers.
//Brute force
#include<iostream>
#include <vector>
using namespace std;

//function to return count of subarrays
//with k odd numbers
int countOddSubarrays(vector<int>& nums, int k) {
    int n = nums.size();
    int count = 0;
    
    //traverse for all possible subarrays
    for (int i = 0; i < n; i++) {
        int oddCount = 0;
        for (int j = i; j < n; j++) {
            if (nums[j] % 2 == 1) {
                oddCount++;
            }
            if (oddCount == k) {
                count++;
            }
        }
    }

    return count;
}

int main(){
    vector<int> nums = {1, 2, 1, 1, 4, 1};
    int k = 3;

    cout << countOddSubarrays(nums, k);
}
Output:
4

Time Complexity: O(n^2), because we are using the nested loop to check all possible subarrays.
Space Complexity: O(1), as it does not use any extra space to solve this problem.

Approach 2: Sliding Window Approach.

In this approach, we begin by initializing two pointers, start and end, both pointing to the first element of the array. Additionally, we set count and ans to zero. 

The next step involves traversing the array using the end pointer. During this traversal, we increment the count variable if the element is odd. We then slide the window to the right until the count becomes equal to k.

With each step, we update the ans variable to keep track of the number of subarrays containing exactly k odd integers. Eventually, we return the value of ans.

To calculate the number of subarrays with exactly k odd integers, we compute the difference between the number of subarrays with less than k odd integers and the number of subarrays with at most k-1 odd integers. Remarkably, we can leverage the same subArray function to compute both of these values efficiently.

Below is the C++ code implementation for the above approach.
//C++ code to Count Subarrays with K Odd Numbers.
//Sliding window approach
#include<iostream>
#include <vector>
using namespace std;

int subArray(vector<int>& nums, int k) {
    int count = 0, ans = 0, start = 0, end = 0;
    int n = nums.size();

    // Sliding window approach
    while(end<n){
        if(nums[end]%2==1){
            count++;
        }
        // Shrink the window until the count 
        //becomes less than or equal to K
        while(count>k){
            if(nums[start]%2==1){
                count--;
            }
            start++;
        }
        ans += end-start+1;
        end++;
    }
    return ans;
}
// Function to count the number of 
//subarrays with K odd numbers
int countOddSubarrays(vector<int>& nums, int k) {
    /*
    difference between number of subarrays with at most k-1
    odd elements with number of subarrays with at most k
    odd elements
    */
    return subArray(nums, k) - subArray(nums, k - 1);
}

int main(){
    vector<int> nums = {2, 1, 9, 3, 1};
    int k = 2;

    cout << countOddSubarrays(nums, k);
}
Output:
4

Time Complexity: O(n)
Space Complexity: O(1)

Sliding Window Algorithm with Example

The sliding Window Algorithm helps us solve many simple and complex coding problems with an optimized approach and lesser time complexity. In most cases, we use the sliding window algorithm to reduce the use of nested loops and the repetitive work that we do while solving any problem. 

Sliding Window Algorithm

Why it is called Sliding Window Algorithm?

When we solve problems using this Sliding Window algorithm we try to create or find fixed-size or variable-size windows (here window is nothing but a subarray or substring) which satisfies the given condition of the problem and then we keep sliding the window by one unit to cover next subarrays. 

We can easily find the required window (subarray) using two nested loops but the sliding window algorithm helps us find all possible windows by using a single loop and here now it helps us reduce our time complexity. The name of this algorithm is quite interesting and when we start visualizing the solution using this algorithm then everyone gets satisfied with the name of this algorithm. 


When should we use Sliding Window Algorithm?

Whenever we want to use some algorithm to solve any particular problem we should always be trying to find some pattern in the given question like when we want to apply a binary search algorithm then we try to check whether the given array is sorted or not. 

There are a few points that you can check for before using the sliding window algorithm:

  • There should be some discussion related to subarray or substring in the given problem.
  • There should be some discussion related to finding the largest, smallest, maximum, minimum, or any count.
  • The problem might give us a window size denoting with variable k but if the window size is not given then it means we need to find the window size based on the given conditions.


Types of Sliding Windows.

We can solve several varieties of coding problems using the sliding window algorithm but more or less we can divide them into two different categories.

  • Fixed Size Sliding Window: In this type, the size of the window (subarray) is static for the entire duration of the program and already given in the problem. 
  • Variable Size Sliding Window: In this type, the size of the window (subarray) is dynamic and keeps on changing for the entire duration of the program and we need to calculate the required largest or smallest window size.  

Example of Fixed-size sliding window

Given an array of integers of size n, find the minimum sum of the subarray of size k. 

Example 1:

Input: arr[] = {2, 3, 5, 4, 9, 7, 1}  k = 3
Output: 10

Explanation: 
Sum of all possible subarrays of size 3
{2, 3, 5} = 2+3+5 = 10
{3, 5, 4} = 3+5+4 = 12
{5, 4, 9} = 5+4+9 = 18
{4, 9, 7} = 4+9+7 = 20
{9, 7, 1} = 9+7+1 = 17 
The minimum sum we get by adding the subarray {2, 3, 5} of size 3.

Example 2:

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

Explanation:
The minimum sum we get by adding the subarray {-3, 2} of size 2

We can easily solve this problem using a brute force approach by running two nested loops for calculating the sum of all possible subarrays of size k and returning the minimum sum out of all possible. Time Complexity for this approach is O(n*k) where n is the number of elements and k is the size of the subarray.


Below is the code for the brute force approach:

//C++ Code for minimum sum of subarray of size k (O(n*k) solution)
#include<iostream>
using namespace std;

int minSubarraySum(int arr[], int n, int k){

    int minSum = INT_MAX;

    for(int i = 0; i < n-k; i++){
        int sum = 0;
        for(int j = i; j < i+k; j++){
            sum += arr[j];
        }
        minSum = min(minSum, sum);
    }
    return minSum;
}
int main(){
    int arr[] = {5, -3, 2, 8, 4, 1};
//size of given array int n = sizeof(arr)/sizeof(arr[0]); //size of subarray int k = 3; cout<<minSubarraySum(arr, n, k); }

Output:

4

  • Time Complexity: O(n*k)
  • Space Complexity: O(1)

Now let's check that can we apply the sliding window algorithm to the above problem? As we discussed above for applying the sliding window algorithm, we can check for certain conditions like the problem is saying something about subarray, the window size k is given and we need to find the minimum subarray sum. It means the given problem satisfies all our conditions so we can think about applying the fixed-size sliding window approach here.


Sliding Window Algorithm: For applying the sliding window approach to this kind of problem where the window size is fixed we first need to compute the sum of the first k elements of the array and it will give us one possible answer that we can store in a variable window_sum. Now to slide the window by one unit to the right we need to remove the calculation of the first element of the previous window and add the last element of the current window. 

Sliding window example


We first calculate the initial window_sum starting from index 0 to 0+k and then we store it as a sum of our current window (current_sum) and we update our answer variable min_sum if current_sum is lesser than min_sum (initially min_sum  = INT_MAX). 

  • current_sum = 4
  • min_sum = 4

Fixed Size Sliding window example
Now to get the sum of the next current_window we have to remove the first element from window_sum and add the last element of the current_window. Every time update the value of min_sum if the value of current_sum is smaller than min_sum.

  • current_sum = 7
  • min_sum = 4
Fixed size sliding window example steps

Similarly, again
 to get the sum of the next current_window we have to remove the first (arr[1]) element from window_sum and add the last element (arr[4]) of the current_window.
  • current_sum = 14
  • min_sum = 4

Fixed size sliding window example step 3
  • current_sum = 13
  • min_sum = 4
Below is the code implementation of a fixed-size sliding window:

//C++ Code for minmum sum of subarray of size k (Sliding Window Approach)
#include<iostream> using namespace std; //function to find minmum sum of subarray of size k int minSubarraySum(int arr[], int n, int k){ //variable to store maxSum int minSum = INT_MAX; //variable to calculate window size int i = 0, j = 0; int window_sum = 0; while(j < n){ window_sum = window_sum + arr[j]; //Window size is less than k if(j-i+1 < k){ j++; } /*we get one of the possible answer, store it and remove the calculation of ith element and slide the window by one unit*/ else if(j-i+1 == k){ minSum = min(minSum, window_sum); window_sum = window_sum - arr[i]; i++; j++; } } return minSum; } int main(){ int arr[] = {5, -3, 2, 8, 4, 1}; //size of given array int n = sizeof(arr)/sizeof(arr[0]); //size of subarray int k = 3; cout<<minSubarraySum(arr, n, k); }
Output:
4
  • Time Complexity: O(n)
  • Space Complexity: O(1)

After solving many fixed-size sliding window problems, I have observed a general pattern for this algorithm that you can also follow while solving problems.

Fixed-size Sliding Window General Format

while(j < n)
{
    /*
    In this step, we need to do calculation for 
    window formation base on given condition.
    */
    if(current_window_size < k)
       /*
       Increase the window size as it is 
       not equal to given window size k
       */
       j++;
    else if(current_window_size == k)
    {
        /*
        We get our one possible answer so store
        them in some answer variable 
        */
        /*
        Remove the calculation of ith index to 
        slide the window one unit right
        */
        /*
        Increment the vlaue of i and  j to maintain
        the window size 
        i++;
        j++;
        */
    }   
}
return answer;


Example of Variable-size sliding window

Given an integer array of size n, find the length of the longest subarray having a sum equal to k.

Example 1:

Input: arr[] = {8, 7, 3, 6, 1, 5}  k = 15
Output: 4

Explanation: 
The longest subarray with sum 15 is {3, 6, 1, 5}

Example 2:

Input: arr[] = {1, 2, 3} k = 3
Output: 2

Explanation:
The longest subarray with sum 5 is {1, 2}

Input: arr[] = {-5, 7, -14, 3, 4, 12} k = -5
Output: 5

Brute Force: We find the sum of all possible subarrays and return the length of the longest subarray having a sum equal to k. The time complexity of this approach is O(n^2) as we are calculating the sum of all subarrays.


Below is the C++ Code Implementation.

#include<iostream>
using namespace std;

//function to find longest subarray of sum k
int longestSubarraySum(int arr[], int n, int k){
    //variable to store answer
    int maxlen = 0;

    for(int i = 0; i < n; i++){
        int sum = 0;
        for(int j = i; j < n; j++){
            sum += arr[j];

            if(sum == k){
                maxlen = max(maxlen, j-i+1);
            }
        }
    }
    return maxlen;
}

int main(){
    int arr[] = {10, 5, 2, 7, 1, 9};
    //given array size
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 15;
    cout<<longestSubarraySum(arr, n, k);
}
Output:
4
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
Let's check if can we apply the sliding window algorithm to this problem. If we go through the problem description we observe that it tells us to find subarrays for a given condition and return the longest one out of them. Here the size of the window is not fixed as we need to find the longest possible subarray. Now we can think of variable-size sliding windows.

Sliding Window Algorithm: (This approach will not work for arrays containing negative numbers).
In this problem where the Window size is not fixed, we will get three conditions to handle:
  • When the sum is less than k, we need to add more variables and increment j.
  • When the sum is equal to k, we get one possible answer and store the length of the current subarray in some max variable.
  • When the sum is greater than k, then subtract the ith elements until the sum becomes less than k.
Below is the C++ Code Implementation of the variable size sliding window approach.

#include<iostream>
using namespace std;

//function to find longest subarray of sum k (Sliding Window approach)
int longestSubarraySum(int arr[], int n, int k){
    //variable to store answer
    int i = 0, j = 0, sum = 0;
    int maxlen = INT_MIN;

    while(j < n){
        sum += arr[j];
        //sum is less than k
        if(sum < k){
            j++;
        }
        //sum is equal to k
        else if(sum == k){
            maxlen = max(maxlen, j-i+1);
            j++;
        }
        //sum is greater than k
        else if(sum > k){
            //remove ith elements until sum 
            //again become equal or less than k
            while(sum > k){
                sum -= arr[i];
                i++;
            }
            if(sum == k){
                maxlen = max(maxlen, j-i+1);
            }
            j++;
        }
    }
    return maxlen;
}

int main(){
    int arr[] = {10, 5, 2, 7, 1, 9};
    //given array size
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 15;
    cout<<longestSubarraySum(arr, n, k);
}
Output:
4
  • Time Complexity: O(n)
  • Space Complexity: O(1)

After solving many variable-size sliding window problems, I have observed a general pattern for this algorithm that you can also follow while solving problems.

Variable-size Sliding Window General Format

while(j < n)
{
    /*
    we need to do [calculation] for window 
    formation base on given condition.
    */
    if(calculation < k)
    {
       /*
       Increase the window size as calculation
       is not matching with given condition k
       */
       j++;
    }   
    else if(calculation == k)
    {
        /*
        we get our one possible answer, store them in some variable
        Increment the value of j.
        */
    }
    else if(calculation > k)
    {
        /*
        start removing ith elements to from calculation
        so it again meet our condition calculation == k
        */
        while(condition > k)
        {
            //remove calculation for i
            i++;
        }
        //check if we are meeting the given condition
        j++;
    }   
}
return answer;

Static sliding windows and Dynamic sliding windows, both are totally two different cases of sliding window problems and both should be handled differently.

Sliding Window Problems:

Find Maximum Sum of a Subarray of size K.

Given an integer array of size n and a number k, find the maximum sum of a subarray of size k

Example 1:

Input: arr[] = {2, 3, 5, 2, 9, 7, 1}  k = 3
Output: 18

Explanation: 
Sum of all possible subarrays of size 3
{2, 3, 5} = 2+3+5 = 10
{3, 5, 2} = 3+5+2 = 10
{5, 2, 9} = 5+2+9 = 16
{2, 9, 7} = 2+9+7 = 18
{9, 7, 1} = 9+7+1 = 17 
The maximum sum we get by adding the subarray {2, 9, 7} of size 3.

Example 2:

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

Explanation:
The maximum sum we get by adding the subarray {8, 4} of size 2


Approach 1: Brute Force

We can run two nested loops to calculate the sum of possible subarrays of the given size k and return the maximum of all sums. The time complexity of this approach will be O(n*k) where n is the number of elements in the array and k is the size of the subarray. 


C++ Code for finding the maximum sum of a subarray of size k.

//C++ Code for maximum sum of subarray of size k 
#include<iostream>
using namespace std;

int maxSubarraySum(int arr[], int n, int k){

    int maxSum = INT_MIN;

    for(int i = 0; i < n-k; i++){
        int sum = 0;
        for(int j = i; j < i+k; j++){
            sum += arr[j];
        }
        maxSum = max(maxSum, sum);
    }
    return maxSum;
}
int main(){
    int arr[] = {2, 3, 5, 2, 9, 7, 1};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    //size of subarray
    int k = 3;
    cout<<maxSubarraySum(arr, n, k);
}
Output:
18
  • Time Complexity: O(n*k)
  • Space Complexity: O(1)
Our brute force approach will work fine for a smaller value of k but as soon as the k value goes high our time complexity will also increase. We have to think of an optimized approach and we need to check that is there any repetitive work we are doing? 
 
Approach 2: Fixed-size Sliding Window (Optimized approach).

If we observe carefully we notice that the time taken to calculate the sum of each subarray is O(k) but we can compute this calculation in O(1) time complexity for all the subarray except the first subarray of size k. 

Here we are going to use the fixed-size sliding window concept to optimize our solution where the size of our Window is given as k. First, we are going to calculate the sum of our first subarray (window) of size k, and to get the sum of the next subarray we are going to add the next element in the current sum and remove the first element of the last window. 

C++ Code for finding the maximum sum of a subarray of size k using the Sliding Window Approach.
//C++ Code for maximum sum of subarray of size k (optimized)
#include<iostream> using namespace std; //function to find maximum sum of subarray of size k int maxSubarraySum(int arr[], int n, int k){ //variable to store maxSum int maxSum = INT_MIN; //variable to calculate window size int i = 0, j = 0; int sum = 0; while(j < n){ sum = sum + arr[j]; //Window size is less than k if(j-i+1 < k){ j++; } /*we get one of the possible answer, store it and remove the calculation of ith element and slide the window by one unit*/ else if(j-i+1 == k){ maxSum = max(maxSum, sum); sum = sum - arr[i]; i++; j++; } } return maxSum; } int main(){ int arr[] = {2, 3, 5, 2, 9, 7, 1}; //size of given array int n = sizeof(arr)/sizeof(arr[0]); //size of subarray int k = 3; cout<<maxSubarraySum(arr, n, k); }
Output:
18
  • Time Complexity: O(n)
  • Space Complexity: O(1)

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson