Pattern · 8 problems
Sliding Window Interview Problems
A sliding window turns a search over every substring into one pass. I grow the right edge and shrink the left.
Free: write the code and run it, no sign-up.
When I reach for it
- The question asks for the longest, shortest or best stretch of a sequence.
- A rule like "at most k" or "no repeats" decides what counts as valid.
- Brute force would check every substring.
Problems, easiest first
1 easy · 5 medium · 2 hard. Open one to read it, then write it in the free editor.
- Best Time to Buy and Sell StockeasyArrays & Hashing
- Longest Repeating Character ReplacementmediumTwo PointersStrings
- Analytics: Longest Unique Session WindowmediumStrings
- Permutation in StringmediumTwo PointersStrings
- Find All Anagrams in a StringmediumStringsArrays & Hashing
- K Radius Subarray AveragesmediumArrays & Hashing
- Minimum Window SubstringhardStringsArrays & Hashing
- Sliding Window MaximumhardStackHeaps
The idea
Keep a window that stays valid. Grow the right edge each step. When the window breaks the rule, shrink the left edge until it holds again.
Each index enters the window once and leaves once. That is why the scan stays linear even with a loop inside the loop.
left = 0
best = 0
counts = {}
for right, ch in enumerate(text):
counts[ch] = counts.get(ch, 0) + 1 # grow: add the new item
while counts[ch] > 1: # the window broke the rule
counts[text[left]] -= 1 # shrink: drop from the left
left += 1
best = max(best, right - left + 1) # record the best valid windowWhere it goes wrong
- Recording the answer before the window is valid again.
- Forgetting to take the left item out of your counts when you shrink.
- Sums with negative numbers break the shrink step. Reach for prefix sums instead.
Say this before you type. Say what makes the window valid, and what you do to the left edge when it breaks.
Where Coco comes in
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.
Questions people ask
- Fixed window or variable window?
- A fixed window has a size the problem gives you. A variable window grows and shrinks to keep a rule true.
- When does a sliding window fail?
- It fails when dropping the leftmost item cannot restore validity. Sums with negative numbers are the classic case.
Meet these next
Fin and Coco are characters, not people. strongyes.io is independent. Leo builds it with AI agents.
