About

ssss

Saturday, April 3, 2021

thumbnail

Pattern - 1:Sliding Window

This pattern is used when any problem statement has something like calculate(sum , avg, max, math,duplicate) with in subarray,sublist and substring (widow).

Technique: 

    • Keep Increasing the window if the computed value is less than the given  criteria.
    • Print the computed value if criteria is exactly met.
    • keep Decreasing  the window   if the computed value is more than the given criteria.                                          

General snippet of Code:

int slidingWindowPattern(int[] nums , int k){

int windowStart = 0;
int ComputeValue = 0;

for(int windowEnd = 0; windowEnd < nums.length; windowEnd++){

int endValue = nums[windowEnd];
ComputeValue += endValue;// Keep adding the value

if(windowEnd > k){
int startValue = nums[windowStart];
ComputeValue -= startValue;
}
}
return ComputeValue;
}


Example 1 - Easy:

Given an input array nums , find the sum of all subarray of size k.

Input:
nums = [1, 2, 3, 4, 5, 6, 7] k = 3
Output:
result = [6, 9, 12, 15, 18]

Explanation:

First Window : 1 + 2 + 3 = 6 

Second Window : 2 + 3 + 4 = 9

Third Window : 3 + 4 + 5 = 12

Fourth Window : 4 + 5 + 6 = 15

Fifth Window : 5 + 6 + 7 = 18




Solution :

As discussed above , 

  • keep increasing the window until the size of the window is less than K by storing the summation of all elements into a computed sum variable  . 
  • If the window size is equal to K then we store into result array .
  • If the window is greater than K then we shrink the window by removing the starting window element from the summation variable.

int[] findSumOfSubArrayOfSizeK(int[] nums, int k){

int[] result = new int[nums.length - (k - 1)];
int windowStart = 0;
int ComputeSum = 0;

for(int windowEnd = 0; windowEnd < nums.length; windowEnd++){

int endValue = nums[windowEnd];
ComputeSum += endValue;// Keep Increasing the window if the computed value is less than the given criteria

if(windowEnd >= k - 1){
int startValue = nums[windowStart];
result[windowStart++] = ComputeSum; //Add the computed sum if criteria is met.
ComputeSum -= startValue;//keep Decreasing the window if the computed value is more than the given criteria.
}
}
return result;
}

About

Search This Blog

Blog Archive

Powered by Blogger.