Sliding Window Technique and 7 Problems to Master it

Sliding Window Technique and 7 Problems to Master it

Β·

2 min read

Sliding window is a really popular technique used to solve complex problems related to Strings and Arrays. It generally reduces the time complexity of a solution from O(N2) to O(N).

The idea is to make a window of certain length that will satisfy the problem constraints. Generally, the window is represented with 2 pointers --- Left and Right --- that points to a specific index in the Array or a specific character in the case of a String.

The window down scales based on the problem and it continues to do so until the window either reaches the end of the Array / String or it finds the answer, in which case it returns.

SLidingWindow.webp

Example for better Understanding

Input : arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k = 3

Output : 117

We get maximum sum by adding subarray {15, 12, 90} of size 3.

Solution

class Main {

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

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

        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        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;
    }

    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
        int k = 4;
        int n = arr.length;
        System.out.println(maxSum(arr, n, k));
    }
}

Practice on these

  1. Remove All Adjacent Duplicates In String

  2. Contains Duplicate II

  3. Longest Substring Without Repeating Characters

  4. Maximum Length of Repeated Subarray

  5. Find K Closest Elements

  6. Find All Anagrams in a String

  7. Longest Repeating Character Replacement

Thank you for reading till the end, if you like this blog then please

share it with your friends so that they can also learn and grow with you 😊.

Did you find this article valuable?

Support Varchasv Hoon by becoming a sponsor. Any amount is appreciated!

Β