If you have ever written nested loops to check every possible subarray and watched your code time out during an online assessment, you need the sliding window pattern. At its core, sliding window is an optimization technique that transforms $O(N^2)$ or $O(N^3)$ brute-force solutions into elegant $O(N)$ algorithms. It achieves this by reusing the work done in previous steps rather than recalculating overlapping data from scratch. In Indian tech interviews, from service companies' coding rounds to Amazon and Flipkart, this pattern is a staple for string and array manipulation rounds.
When to use this pattern
Recognizing when to apply the sliding window pattern is half the battle. Interviewers rarely tell you to use it directly. Instead, look for these strong signals in the problem statement:
- The "Contiguous" Keyword: The problem asks you to find a "subarray" or "substring". Unlike subsequences (which can skip elements), subarrays and substrings must be strictly contiguous. Sliding window is purpose-built for contiguous elements.
- Min/Max/Longest/Shortest: You are asked to optimize a metric, such as finding the longest substring with a certain property, or the minimum length subarray that sums to a target.
- Linear Data Structures: The input is an array, string, or occasionally a linked list.
- Monotonicity (Crucial for dynamic windows): Adding an element to the window should predictably change the state (e.g., adding positive numbers always increases the sum). If adding an element can either help or hurt unpredictably (like adding negative numbers to a sum), sliding window might fail.
The core idea
Imagine a physical window frame sliding over a sequence of numbers. You can only see the numbers inside the frame.
Instead of picking up the frame and placing it down on every possible starting position (which is what a nested loop does), you slide the right edge of the frame to include a new element, and slide the left edge to remove an old element.
There are two main types of sliding windows:
| Window Type | Characteristic | Example Problem |
|---|---|---|
| Fixed-size | The window size k remains strictly constant. You add one element on the right and remove exactly one on the left. | Maximum sum of a contiguous subarray of size k. |
| Dynamic-size | The window expands on the right until a condition is met (or violated), then shrinks from the left to restore the condition. | Longest substring without repeating characters. |
Here is a visual representation of a dynamic window expanding and shrinking:
Template
Memorizing a robust template prevents off-by-one errors during high-pressure interviews. Here is the standard template for a dynamic sliding window.
def sliding_window_template(arr):
left = 0
best_ans = 0 # or float('inf') for minimums
for right in range(len(arr)):
# 1. Add the current element arr[right] to the window state
# 2. While the window violates the problem's condition, shrink it
while invalid_condition():
# Remove arr[left] from the window state
left += 1
# 3. Update the best answer (can also happen inside the while loop for some problems)
best_ans = max(best_ans, right - left + 1)
return best_ansWorked examples
Let's apply this template to three classic interview problems.
1. Longest Substring Without Repeating Characters
Problem: Given a string s, find the length of the longest substring without repeating characters.
Approach: We use a dynamic sliding window. We maintain a set (or a boolean array/hash map) to keep track of the characters currently in our window.
- We expand the window by moving
rightand addings[right]to our set. - If
s[right]is already in the set, our window is invalid. We must shrink the window from theleftuntil the duplicate character is removed. - At the end of each valid step, we update our maximum length.
def lengthOfLongestSubstring(s: str) -> int:
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
# While the character is already in the window, shrink from left
while s[right] in char_set:
char_set.remove(s[left])
left += 1
# Add the current character and update max_len
char_set.add(s[right])
max_len = max(max_len, right - left + 1)
return max_lenComplexity:
- Time: $O(N)$ where $N$ is the length of the string. Each character is processed at most twice (once added, once removed).
- Space: $O(min(N, M))$ where $M$ is the size of the character set (e.g., 26 for lowercase English letters, 128 for ASCII).
2. Minimum Size Subarray Sum
Problem: Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there is no such subarray, return 0.
Approach: This problem asks for a minimum length, which slightly changes where we update our answer.
- Expand the window by adding
nums[right]to a runningwindow_sum. - When
window_sum >= target, our condition is met! Since we want the minimum length, we record the current window length, and then try to shrink the window from the left to see if we can find an even smaller valid window.
def minSubArrayLen(target: int, nums: list[int]) -> int:
left = 0
window_sum = 0
min_len = float('inf')
for right in range(len(nums)):
window_sum += nums[right]
# While the window is valid, record the answer and try to shrink it
while window_sum >= target:
min_len = min(min_len, right - left + 1)
window_sum -= nums[left]
left += 1
return min_len if min_len != float('inf') else 0Complexity:
- Time: $O(N)$ because the left and right pointers only move forward.
- Space: $O(1)$ as we only use a few integer variables.
3. Max Consecutive Ones III
Problem: Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k 0s.
Approach:
Instead of thinking about "flipping" zeroes, reframe the problem: Find the longest contiguous subarray that contains at most k zeroes.
- Expand the window to the right. If we encounter a
0, increment ourzero_count. - If
zero_count > k, our window is invalid. We must shrink from the left until we remove a0from the window. - Update the maximum length.
def longestOnes(nums: list[int], k: int) -> int:
left = 0
zero_count = 0
max_len = 0
for right in range(len(nums)):
if nums[right] == 0:
zero_count += 1
while zero_count > k:
if nums[left] == 0:
zero_count -= 1
left += 1
max_len = max(max_len, right - left + 1)
return max_lenVariations and pitfalls
The Negative Number Trap
In the Minimum Size Subarray Sum problem above, we explicitly stated the array contained positive integers. Why? Because with positive integers, expanding the window guarantees the sum increases, and shrinking it guarantees the sum decreases. This monotonicity is what allows us to safely move the left pointer.
If the array contains negative numbers (e.g., [3, -1, 4, -2, 5]), adding an element might decrease the sum. You can no longer guarantee that shrinking the window is the right move when the sum exceeds the target. If you see negative numbers in a subarray sum problem, immediately abandon the sliding window and switch to Prefix Sums and Hashing.
Where to update the answer
Notice the difference between Example 1 (Longest Substring) and Example 2 (Minimum Subarray Sum):
- When finding a maximum, we update the answer outside the
whileloop, after the window has been made valid. - When finding a minimum, we update the answer inside the
whileloop, because thewhileloop condition itself represents a valid state that we are trying to minimize.
Fixed-size windows
Sometimes the problem dictates a fixed window size k. In these cases, you don't need a while loop to shrink the window. Instead, you check if right - left + 1 == k. If it is, you record the answer, remove the left element, and increment left by 1.
Practice checklist
To truly master this pattern, try solving these variations on your own:
- Fixed Window: Find the maximum average subarray of size
k. - String Anagrams: Find all starting indices of anagrams of string
pin strings(requires a frequency map as the window state). - Multiple Conditions: Longest substring with at most
kdistinct characters.
Once you internalize the template and understand the negative number pitfall, sliding window problems will become some of the easiest and most predictable questions you can encounter in an interview.