“Find the longest substring without repeating characters.” “Find the maximum sum of k consecutive days.” If a question talks about a stretch of an array or string, it's almost always the sliding window technique, one of the top two patterns in coding interviews.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stackcoming soon
- 8Heap / Top-Kcoming soon
- 9Tree Patternscoming soon
- 10Grid BFS & Topological Sortcoming soon
- 11Backtrackingcoming soon
- 12DP Patternscoming soon
The train window story
Sit by the window of a moving train. You can see 3 trees at a time. When the train moves, one new tree appears on the right and one old tree disappears on the left. You don't re-count the trees in the middle; you only notice what enters and what leaves.
That's a sliding window. The simplest kind has a fixed size. Slide it:
☕ Best 3 days of chai sales: slide the window
First window: 12 + 7 + 15 = 34 cups.
You never re-add all three days. Each slide is: previous total + the new day − the day that left. That's one addition and one subtraction, however big the window.
Two kinds of windows
📏 Fixed window (size k)
“Best total of 3 days in a row.” The size never changes. Each slide: add the new item, drop the old.
🪗 Variable window (grows and shrinks)
“Longest stretch with no repeated letter.” Grow on the right; while the rule is broken, shrink from the left.
The variable window is the one interviewers love. Step through it, then try your own name:
🪟 Find the longest stretch with no repeated letter
Grow: add “a”. Window “a” has no repeats. New best length 1! ⭐
Best so far: “a” (length 1)
Watch the pointers: the right one only moves right (grow), the left one only moves right (shrink). Each letter enters once and leaves once, so the total work is O(n), not O(n²).
🔍 Use sliding window when you see
- ✓The words subarray or substring
- ✓Contiguous, consecutive, “in a row”
- ✓Longest / shortest / maximum / minimum stretch
- ✓“At most K” or “exactly K distinct”
🚫 Don't use it when
- ✗You need a pair from anywhere (two pointers or hash map)
- ✗Sum exactly K with negative numbers (prefix sum + hash map)
- ✗Items don't have to be next to each other (subsequence → DP)
The template (the one to memorize)
left = 0
for right in range(len(arr)):
add arr[right] to the window # 1. grow
while window breaks the rule:
remove arr[left]; left += 1 # 2. shrink
best = max(best, right - left + 1) # 3. record⚡ Memory tricks
- 1
“Grow, Shrink, Record” (GSR)
The 3 steps inside the loop, always in this order.
- 2
“Sub-STRING or sub-ARRAY in a row → window”
Contiguous is the magic word.
- 3
“Add the new, drop the old”
For fixed windows: new total = old total + entering − leaving.
- 4
“Left never goes back”
That's why it's O(n): each item enters once and leaves once.
Code: fixed and variable windows (Python, Java, C++)
Both kinds in one file. Outputs in the comments come from running the code.
def best_k_days(sales, k):
"""Fixed window: highest total over any k days in a row."""
window = sum(sales[:k])
best = window
for right in range(k, len(sales)):
window += sales[right] - sales[right - k] # add the new day, drop the oldest
best = max(best, window)
return best
def longest_unique(s):
"""Variable window: longest substring with no repeated letter."""
seen = set()
left = best = 0
for right, ch in enumerate(s):
while ch in seen: # window is broken: shrink from the left
seen.remove(s[left])
left += 1
seen.add(ch) # grow on the right
best = max(best, right - left + 1)
return best
print(best_k_days([2, 1, 5, 1, 3, 2], 3)) # 9 (5 + 1 + 3)
print(longest_unique("abcabcbb")) # 3 ("abc")
print(longest_unique("pwwkew")) # 3 ("wke")One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Maximum Sum Subarray of Size K | Fixed window: add new, drop old | Easy |
| Longest Substring Without Repeating Characters | Variable window + set | Medium |
| Longest Repeating Character Replacement | Window valid while (size − top count) ≤ k | Medium |
| Permutation in String / Find All Anagrams | Fixed window + letter counts | Medium |
| Minimum Size Subarray Sum | Shrink while sum ≥ target | Medium |
| Minimum Window Substring | Grow until all letters covered, then shrink | Hard |
| Sliding Window Maximum | Window + deque of useful indexes | Hard |
🎯 Spot the pattern: is it sliding window?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Find the maximum sum of any 4 consecutive elements.
2. Find the length of the longest substring with at most K distinct characters.
3. Find two numbers in a sorted array whose sum is 50.
4. Find the smallest subarray with sum ≥ 15 (all numbers positive).
5. Count subarrays whose sum is exactly K, numbers may be negative.
🧠 PATH memory card
Remember sliding window for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A train window shows 3 trees. As the train moves, one tree enters on the right and one leaves on the left. You only look at the change.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Train window: Grow, Shrink, Record”
- Train window→A contiguous stretch between left and right
- Grow→Move right forward, add the new item
- Shrink→While the rule is broken, remove from the left
- Record→Update the best answer after each step
- Left never goes back→Total work O(n)
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
"abcabcbb": grow a, ab, abc (best 3) · next “a” repeats → drop a → bca · “b” repeats → drop b → cab · … best stays 3. Do it once on paper with your finger as the left pointer. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Using
ifinstead ofwhileto shrink. One removal may not fix the window; keep shrinking until it's valid. - Recording before shrinking. Always shrink first, then record, or you'll count an invalid window.
- Off by one in the length. The window from left to right holds
right − left + 1items.
Where to go next
Sliding window needs a clear grow/shrink rule, which breaks with negative numbers. For “how many subarrays sum to K” and lightning-fast range sums, the next pattern uses a cricket scoreboard trick: prefix sum with a hash map. (Missed the previous one? See two pointers.)
Key takeaways
- ✓Sliding window = a contiguous stretch between two pointers that both move forward.
- ✓Fixed window: add the new item, drop the old one.
- ✓Variable window: Grow, Shrink (while broken), Record.
- ✓O(n) because each item enters and leaves once.
- ✓Signals: subarray/substring, contiguous, longest/shortest, at most K.
Frequently asked questions
What is the sliding window technique?
A way to look at a contiguous part (a 'window') of an array or string and move it along without recomputing everything. You add the item that enters on the right and remove the item that leaves on the left, so a problem that looks O(n²) becomes O(n).
What is the difference between a fixed and a variable sliding window?
A fixed window always has the same size k, for example 'best total of any 3 days in a row'. A variable window grows and shrinks to keep a rule true, for example 'longest substring with no repeated letter'. Fixed: slide by one each step. Variable: grow on the right, shrink on the left while the rule is broken.
How do I know a problem needs a sliding window?
Look for the words subarray or substring together with contiguous, consecutive, longest, shortest, maximum or minimum, or 'at most K'. If the answer is one unbroken stretch of the input, think sliding window.
What is the time complexity of sliding window?
O(n) time, because the right pointer moves n times and the left pointer moves at most n times in total. Extra space is O(1) for sums or O(k) for a set or map holding the window's characters.
Does sliding window work with negative numbers?
For 'subarray with sum exactly K' when numbers can be negative, no: adding a number might make the sum smaller, so you don't know whether to grow or shrink. Use prefix sum with a hash map instead, which is the next lesson.
🧠 Quick check: sliding window
1. Which question is a sliding window problem?
2. In a variable window, the rule breaks (a repeated letter enters). What do you do?
3. Fixed window of size 3. Old total = 30, new day = 8, day leaving = 5. New total?
4. Why is sliding window O(n) even though it has a loop inside a loop?
Checking your access…