Sliding Window

Imagine that you're allowed to select 3 chocolate chip cookies in a contiguous subarray. Your goal is to find a window of 3 cookies with the most amount of chips!

The same concept can be applied to arrays or strings. The window boundry is defined by the left and right pointers as shown in the picture below:

Sliding window, k = 3

Example:

  1. Find the Maximum of subarray
  2. Detect repeating pattren in a string

There are 2 types of Sliding windows:

1. Fixed Window: Window size k is constant.

eg: Window of 3 cookies with the maximum amount of chips.

Fixed window, k = 3

2. Dynamic window: k changes.

eg: The smallest window with sum ≥ 7 

Dynamic Window

Sliding Window Algorithm

Imagine you have a long line of objects (an array), and you need to look at a fixed-sized group of them (the window, size k) and calculate something (like their sum).

1. The "Brute Force" (The Slow Way)
If you wanted to calculate the sum of every group of k=3 numbers, you would do this:
  •  Calculate the sum of Group 1.
  •  Calculate the sum of Group 2 (restarting the count).
  •  Calculate the sum of Group 3 (restarting the count)....and so on.
This is slow because you are doing a lot of unnecessary work.

2. The "Sliding Window" (The Fast Way)

The "Sliding Window" is a smart shortcut. Instead of restarting the calculation for the new group, you simply update the result from the previous group.
Steps:
Calculate the First Group: You calculate the sum of the very first window of size k (e.g., 1+5+2 = 8). This gives you your starting point.
   
 Slide: When you move the window one step to the right, only one number leaves and one new number enters.
   * Subtract the Old: Take the number that just left the group and subtract it from your current sum.
   * Add the New: Take the new number that just entered the group and add it to your current sum.

Algorithm


   Example:
  •    Array : [3, 4, 5, 3, 2, 7, 8] 
  •    k=3
  •    ProcessWindow =  Maximum sum

  • Window 1 : [3, 4, 5] (Sum: 12)
  • Slide Right: We drop the 3 and pick up the next element 3.
  • New Sum: 12 +3 - 3 =12

Workflow


This way, you find the new sum with just two quick operations (one subtraction and one addition) instead of recalculating all three numbers! You repeat this one-step update until you reach the end of the array.
This makes the algorithm extremely fast!



Comments

Popular posts from this blog

1. Repeated DNA Sequences

Top K Elements

1. Valid palindrome