🌈 Holi Special – Extra 26% OFF on our Professional Courses | Use Coupon HOLI26OFF    Loading... View Courses →

Sliding Window Technique  


Introduction
  • Sliding Window is a technique used to solve problems on arrays or strings.
  • It is a form of the Two Pointers Technique.
  • We create a window (a small part of the array/string) and move it step-by-step.
  • Image
  • This window can be:
    • Fixed Size: The window size remains constant.
    • Variable Size: The window size can expand or contract based on conditions.
  • It helps reduce time complexity from O(n²) to O(n) in many problems.
  • Sliding Window Technique is also used in real-world projects.
    • For example, if you want to calculate how many users visited your website in the last 3 days or the last 24 hours, you can keep a moving window of data and update the count as the window shifts. This helps you get real-time analytics without recalculating everything again.
    • Below is the program for this example.
Programs:-
  • Program 1: Calculate the number of user visits in the last 3 days.
    public class MainApp1
    {
        public static void main(String[] args)
        {
            int[] users = {100,80,40,70,120,90,60};
            int days = 3;
    
            int total=0;
            for(int i=0; i<days; i++)
            {
                total = total + users[i];
            }
    
            System.out.println("Total number of users visited in last 3 days");
            System.out.println(total);
    
            for(int i=1; i<=users.length-days; i++)
            {
                total = total - users[i-1] + users[i+days-1];
                System.out.println(total);
            }
        }
    }
  • Program 2: Maximum sum of a subarray of size k.
    public class MainApp2
    {
        public static void main(String[] args)
        {
            int[] arr = {100,80,40,70,120,90,60};
            int size=3;
    
            int total=0;
            for(int i=0; i<size; i++)
            {
                total = total + arr[i];
            }
    
            int max=total;
            for(int i=1; i<=arr.length-size; i++)
            {
                total = total - arr[i-1] + arr[i+size-1];
                max = Math.max(total, max);
            }
    
            System.out.println("Maximum Sum Subarray : "+max);
        }
    }

Points to Note:
  • Sliding window works only when:
    • Window size is fixed OR variable but valid
    • Elements are added/removed from window
    • Mostly used for subarrays with constraints (length, sum ≤ K, etc.)

Sliding Window Technique Task:

Try to solve the following problems using Sliding Window Technique:

  1. WAP to Find the Sliding Window Maximum
  2. WAP to Find the Subarrays with K Different Integers