Topic 3 Sliding Window
Last updated
Last updated
The Sliding Window technique is a highly efficient approach in programming, particularly useful for solving problems involving arrays or strings. This technique optimizes operations on subsets of data to find results like maximum sum, length, or count of elements. Let's break it down step by step! 🏊♂️
The Sliding Window technique involves maintaining a "window" that moves across a data structure (usually an array or string). This "window" represents a subset of elements, and it can be:
Fixed size: The window size remains constant throughout.
Dynamic size: The window size adjusts based on certain conditions.
Instead of recalculating results for every possible subset, the Sliding Window technique avoids redundant computations by:
Adding the new element entering the window. ➕
Removing the old element leaving the window. ➖
This dramatically reduces computation time and improves efficiency. 🚀
Follow these general steps to apply the Sliding Window technique:
Initialize a window starting at the beginning of the array or string.
Slide the window across the data:
Add new elements entering the window.
Remove old elements leaving the window.
Perform calculations on the current window to update the result.
Return the final result after processing all possible windows.
k
💰Find the maximum sum of any contiguous subarray of size k
in an array.
Input: arr = [2, 3, 5, 2, 9, 7, 1]
, k = 3
Sliding Window Steps:
[2, 3, 5]
→ sum = 10
[3, 5, 2]
→ sum = 10
[5, 2, 9]
→ sum = 16
[2, 9, 7]
→ sum = 18 ✅
[9, 7, 1]
→ sum = 17
Maximum sum: 18
Find the length of the longest substring without repeating characters in a string.
Input: s = "abcabcbb"
Sliding Window Steps:
Start: a
→ Length = 1
Extend: ab
→ Length = 2
Extend: abc
→ Length = 3 ✅
Repeat: Move start to skip the first a
.
Final: The longest substring is abc
, length = 3
.
Maximum/Minimum Sum Subarray 💵
Longest Substring Problems 🔤
Counting Subarrays/Substrings 🧮
Optimizing algorithms for time and space complexity ⚡
Efficiency: Reduces time complexity from (O(n^2)) to (O(n)) in many problems.
Intuitive: Mirrors how we naturally approach subsets visually.
Widely Applicable: Used in dynamic programming, searching, and optimization problems.
The Sliding Window technique is an essential tool for solving many array and string problems. Mastering it can make complex problems much simpler and your solutions more efficient. Keep sliding and coding! 🎯