Sliding window
Course: Intro Class 2- DSA - chapter 10
https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUqmlE3XX4krYPLPeJEsnR8El-3d7CMHcQEpIpRz3jHA&s
We use sliding window in problems where we have to solve it for** fixed size** subarrays.
We are given an window (subarray) size of K. For each window, we have to compute some value. Using sliding window algorithm, this computation is optimised.
💡 As mentioned, sliding window is only used for fixed sized subarray problems, where you need to compute something for all subarrays of size K. However, this does not mean that the problem has to be directly of this type. Rather, if you are able to reduce the problem to this or a part of the problem involves computation of all subarrays of size K, then you can use sliding window. An example can be Binary search + Sliding window. We will discuss more about this when we learn about Binary search.
The logic is, we should be able to design 2 operations: in and out.
in means being able to add something to the result. add doesn’t mean addition operation, rather if we have a result calculated for a set of elements, how can we recalculate quickly if one element is added to the set.
out means recalculating when one element is removed from the set.
We calculate manually for the first window i.e loop through all the K elements [0, K-1] and calculate the answer. If needed, we maintain some data structure as well.
Now we start with the sliding window algorithm. As the window slides, we can see from the picture one element gets added and one element gets removed. We use our in and out operations respectively to recalculate the answer
For example,
when the window moves for the first time, element at index K is added and element at index 0 is removed. So we call in(K) and out(0)
Example
Section titled “Example”Given an array nums of size n and an integer K, calculate the maximum sum subarray of size K.
Solution
Section titled “Solution”We can use sliding window approach as we have to calculate the sum for every subarray of size K
in : We are maintaining the sum of a set of elements. As new elements are added, we can add them to the sum.
out: As elements are removed we can subtract their values
Code
int sum = 0;int max_sum = 0;// Calculate for first windowfor(int i=0; i<K; i++) sum += arr[i];max_sum = sum;
// Now do sliding windowfor(int i=K; i<n; i++) { // Do in operation sum += arr[i];
// Do out operation sum -= arr[i-K];
// Now we have the updated value for current window. Update ans max_sum = max(max_sum, sum);}