⬅ Previous Topic
Recursion Technique in DSANext Topic ⮕
Two Pointers Technique⬅ Previous Topic
Recursion Technique in DSANext Topic ⮕
Two Pointers TechniqueTopic Contents
The Sliding Window Technique is an optimization strategy for problems involving linear data structures like arrays or strings. It helps reduce the time complexity from O(n²) to O(n) in many cases by avoiding unnecessary re-computation.
Instead of recalculating results for every subarray or substring, we "slide" a window across the structure — updating the result incrementally.
You know the window size (say k
), and the goal is to perform operations over every subarray of size k
.
Find the maximum sum of any subarray of size k
.
class SlidingWindowFixed {
function maxSum(arr, k):
n = length(arr)
windowSum = sum of first k elements
maxSum = windowSum
for i = k to n-1:
windowSum = windowSum + arr[i] - arr[i - k]
maxSum = max(maxSum, windowSum)
return maxSum
}
Window size changes dynamically based on the conditions. You expand the window by moving the right pointer and shrink it by moving the left pointer until conditions are satisfied.
Find the length of the longest substring with at most K distinct characters.
class SlidingWindowVariable {
function longestSubstringWithKDistinct(s, k):
left = 0
right = 0
freqMap = {}
maxLen = 0
while right < length(s):
add s[right] to freqMap
while size of freqMap > k:
decrement freqMap[s[left]]
if freqMap[s[left]] == 0:
remove s[left] from freqMap
left += 1
maxLen = max(maxLen, right - left + 1)
right += 1
return maxLen
}
Problem Statement:
Given a string s
and an integer k
, find the length of the longest substring that contains exactly k
unique characters.
For example:
s = "aabbcc"
, k = 2
→ Output: 4
(longest substrings are "aabb"
, "bbcc"
)s = "aaabbb"
, k = 1
→ Output: 3
(longest substrings are "aaa"
or "bbb"
)s = "abcba"
, k = 2
→ Output: 3
(longest substrings are "bcb"
or "cbc"
)Using a sliding window is efficient for problems that require processing substrings or subarrays. Instead of generating all substrings and checking each, we maintain a dynamic window with exactly k
unique characters and slide it to explore new substrings.
left
and right
for the sliding window.charCount
to count characters in the window.right
and updating charCount
.k
, shrink the window by moving left
.k
unique characters are found.// Function to find longest substring with k unique characters
function longestKUniqueSubstring(s, k):
left = 0
right = 0
maxLen = 0
charCount = empty map
while right < length of s:
// Add current character to map
charCount[s[right]] += 1
// If unique characters > k, shrink window
while size of charCount > k:
charCount[s[left]] -= 1
if charCount[s[left]] == 0:
remove s[left] from charCount
left += 1
// If exactly k unique characters, update maxLen
if size of charCount == k:
maxLen = max(maxLen, right - left + 1)
right += 1
return maxLen
This approach dynamically adjusts the window and ensures that we are always considering substrings with at most k
unique characters. When exactly k
are present, we update the maximum length seen so far.
k
unique characters in the hash map.Sliding window techniques like this are crucial in substring problems where the window size or character frequency needs to be tracked. It’s much more efficient than brute-force methods and can be easily adapted to variations of the problem.
The Sliding Window technique is a must-know strategy for solving linear structure problems efficiently. It transforms brute-force nested loop solutions into linear-time solutions by reusing previous computations. Mastering fixed and variable window problems unlocks a broad class of optimization problems in DSA interviews and competitive programming.
⬅ Previous Topic
Recursion Technique in DSANext Topic ⮕
Two Pointers TechniqueYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.