What is the Sliding Window Technique?
Patterns·6 min·Python code
Sliding window keeps a moving range over an array or string and updates it one element at a time. That reuse cuts an O(n²) scan over every range down to one O(n) pass.
Reusing the Overlap Between Windows
Brute force finds the maximum sum of every size k subarray by adding k numbers, sliding over one place and adding k numbers again, which costs O(n × k). Neighbouring windows share all but two elements, and the pattern uses that overlap.
When the window moves one step right, you subtract the leaving element and add the entering one. Every move costs O(1), so the full scan costs O(n).
Carry information forward instead of rebuilding it, and you have the core idea. Everything else is bookkeeping, like a rolling sum, a character count or a hash set of what sits inside the window.
Fixed Size and Variable Size Sliding Windows
Fixed size windows keep a constant length k. Both edges advance together and you report an answer at every position, like the maximum sum of size k or the average of every k readings.
Variable size windows grow and shrink to meet a condition. You expand the right edge to pull in new elements, and when the window breaks its constraint you contract from the left with a while loop until the constraint holds again.
Longest substring without repeating characters and smallest subarray with a sum of at least a target are variable window problems. Pair them with a hash table or counter that records what the window holds.
How to Spot a Sliding Window Problem
Look for a contiguous subarray or substring and a request for the longest, shortest, maximum, minimum or a count over ranges. Phrases like of size k or at most K distinct are strong signals.
Naive solutions that repeat work across overlapping ranges point to a window. If the target need not be contiguous, the pattern cannot help and dynamic programming fits better.
Apply the pattern on CodeStory's sliding window practice problems.
Sliding Window Code Example in Python
def longest_unique_substring(s: str) -> int:
seen = {} # char -> most recent index
left = 0
best = 0
for right, ch in enumerate(s):
# If ch repeats inside the window, jump left past its last spot
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1
seen[ch] = right
best = max(best, right - left + 1)
return best
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Sliding Window Time and Space Complexity
| Time | O(n) |
|---|---|
| Space | O(1) to O(k) |
Time stays O(n) in every case because both pointers only move forward, so every element enters and leaves once. Space is O(1) for rolling sums and fixed windows, and O(k) when a hash set or map tracks the distinct elements, where k is the window size or alphabet size.
Watch Sliding Window Step by Step
Seeing a window glide across your own input shows when it grows or shrinks. Follow either of these one step at a time.
When to Use Sliding Window
- Finding the maximum, minimum or average of any contiguous subarray of fixed size k.
- Finding the longest or shortest substring or subarray that meets a condition, like no repeats or at most K distinct values.
- Counting or measuring something across every contiguous window, like anagram matches or streaming averages.
- Replacing nested loops over contiguous ranges whose inner work overlaps between neighbours.
Mistakes to Avoid
- Using it when the answer need not be contiguous, because subsets and non adjacent selections need dynamic programming or another approach.
- Shrinking with if instead of while. Variable windows must contract from the left until the constraint holds again before you record an answer.
- Assuming it works with negative numbers when shrinking on a sum. Smallest subarray with a sum of at least a target needs sums to grow as you add values, and negatives break that, so use prefix sums instead.
Sliding Window FAQs
Is the sliding window technique hard to learn?
No. Fixed size windows are quick to grasp once the reuse the overlap idea clicks. Variable size windows are trickier because of the shrink logic, and watching the pointers move makes that logic clear.
When should I use sliding window instead of two pointers?
Use a window when both pointers move in the same direction across a subarray or substring and you track a sum or count. Use plain two pointers when pointers converge from both ends, like on a sorted array.
What is the time complexity of the sliding window algorithm?
O(n), because every element enters and leaves at most once. Space is O(1) for a rolling sum and O(k) when a hash set or map holds window contents.
Does sliding window work with negative numbers?
Fixed size windows work, since you add and subtract values whatever the sign. Variable windows that shrink on a sum threshold break, because adding a value no longer guarantees a bigger sum. Use prefix sums there.
What is the difference between a fixed and a variable sliding window?
Fixed windows keep length k and both edges move together. Variable windows grow on the right and shrink on the left until a condition holds, like no repeated characters.
Which problems use a sliding window?
Maximum sum subarray of size k, longest substring without repeating characters, smallest subarray with a given sum and anagram search all fit the pattern.
How do I practise sliding window on CodeStory?
Watch max sum of k and longest unique substring move in CodeStory's visualisers, then work through CodeStory's sliding window practice problems.
Related Guides
Guides are step one. In a CodeStory batch you code the window yourself, then explain every shrink step in a scored mock round.
Talk to a Mentor