Sliding Window —
One pass. Every subarray.
The sliding window technique lets you process every contiguous subarray of an array in a single O(n) pass — no nested loops. Instead of recalculating from scratch each time, you slide a window forward: add the new element on the right, remove the old element on the left. Watch the window expand and contract in real time on LearnBug and the pattern becomes unforgettable.
What is the Sliding Window Technique?
A sliding window is a contiguous subarray that moves across the input one step at a time. You maintain two pointers — left and right — that define the window boundaries. As right advances, the window grows. When a condition is violated, left advances to shrink it. The key insight: you never process an element more than twice, giving you O(n) instead of O(n²).
Why visualization changes everything
In code, it's hard to see which elements are "inside" the window at any given moment. On LearnBug, the window is highlighted as a live coloured band on the array — you watch it grow one cell to the right, then shrink from the left when the condition breaks. The running sum or count updates in real time beside it. The O(n) behaviour becomes obvious the moment you watch it.
Fixed window vs variable window
Every sliding window problem is one of these two types. Recognise which and the solution follows directly.
Fixed Size Window
Window size k is given. Slide it one step at a time: add the incoming right element, subtract the outgoing left element. The window never changes size. Classic problems: Max sum subarray of size k, average of all subarrays of size k.
Variable Size Window
No fixed size — the window grows when a condition is satisfied and shrinks when violated. right always advances; left advances only when needed. Classic problems: Longest substring without repeating characters, minimum window substring.
Fixed window — Max sum of size k
Array: [2, 1, 5, 1, 3, 2], k = 3. Find the maximum sum of any subarray of size 3.
Build the first window
Sum the first k elements: 2 + 1 + 5 = 8. This is the initial window. Set max_sum = 8.
Window sum = 8 | max = 8
Slide right — add 1, remove 2
Advance the window: sum = 8 - 2 + 1 = 7. No new max. Key insight: one subtraction + one addition, no loop.
Window sum = 7 | max = 8
Slide right — add 3, remove 1
sum = 7 - 1 + 3 = 9. New max! Update max_sum = 9.
Window sum = 9 | max = 9 ✓
Slide right — add 2, remove 5
sum = 9 - 5 + 2 = 6. No new max. Window has reached the end — return 9.
Window sum = 6 | max = 9 ✓ Final answer
Variable window — Longest substring without repeats
String: "abcab". Find the longest substring with no repeated characters.
Expand right — add 'a', 'b', 'c'
No repeats yet. Window = "abc", length 3. Track characters in a set: {a, b, c}.
max length = 3
Right hits 'a' — duplicate! Shrink from left
'a' already in set. Move left right, remove 'a' from set. Now window = "bc", set = {b, c}. Then add new 'a'.
max length = 3
Right hits 'b' — duplicate again! Shrink
'b' in set. Remove 'b', advance left. Window = "ca". Add new 'b'. Final window = "cab", length 3.
max length = 3 ✓ Final answer: "abc" or "bca" or "cab"
Both patterns in code
def max_sum_fixed_window(nums, k):
window_sum = sum(nums[:k]) # first window
max_sum = window_sum
for i in range(k, len(nums)):
window_sum += nums[i] # add incoming right
window_sum -= nums[i - k] # remove outgoing left
max_sum = max(max_sum, window_sum)
return max_sumdef longest_unique_substring(s):
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in char_set: # duplicate found
char_set.remove(s[left]) # shrink from left
left += 1
char_set.add(s[right]) # expand right
max_len = max(max_len, right - left + 1)
return max_lenTime & Space Complexity
When to reach for sliding window
Problem mentions a subarray or substring
Any time you need to find the longest, shortest, max, or min over a contiguous subarray or substring, sliding window is your first instinct.
A fixed window size k is given
If the problem gives you a window size, use fixed sliding window. Compute the first window, then slide — O(n) guaranteed.
You need to track a condition over a range
Counting distinct characters, checking for anagrams, finding a sum ≤ target — all are variable window problems with a condition to maintain.
Brute force uses a nested loop over subarrays
If your O(n²) solution has an outer loop for start and inner loop for end, it's almost always replaceable with a sliding window in O(n).
Frequently asked questions
What is the difference between sliding window and two pointer?
Both use two indices on an array, but sliding window specifically maintains a contiguous subarray and tracks an aggregate (sum, count, max) over it. Two pointer is more general — it often looks for a pair satisfying a condition without caring about the subarray between them. When you're tracking a running total or frequency over a window, call it sliding window. When you're comparing or pairing elements from two ends, call it two pointer.
Does the array need to be sorted for sliding window?
No. Unlike two pointer (opposite ends), sliding window does not require a sorted array. The window just needs to be contiguous — it works on any array or string. In fact, most sliding window problems (longest substring, max sum) are on unsorted input.
Why is the variable window still O(n) if the left pointer moves inside a while loop?
Because left only ever moves forward and never goes backward. Across the entire run of the algorithm, left advances at most n times in total — regardless of how the inner while loop is structured. Each element enters the window once (when right passes it) and exits once (when left passes it). Total operations: 2n = O(n).
What data structure do I use inside the window?
It depends on what you're tracking. For sums: just an integer. For character or element frequency: a hash map (dict or Counter). For uniqueness: a set. For ordering (like sliding window maximum): a deque. The window boundaries are always just two integer indices — the data structure tracks what's inside the window.
What are the most common sliding window interview problems?
Maximum sum subarray of size k, longest substring without repeating characters, minimum window substring, find all anagrams in a string, permutation in string, fruits into baskets, longest subarray with ones after replacement, and sliding window maximum. If you can solve these seven, you've covered every sliding window pattern that appears in interviews.
Watch the window slide on your own code
Paste your subarray problem into LearnBug and see the window expand and contract step by step.