Pattern · Interview prep
Sliding Window
Keep a moving slice of an array or string and update it as its ends move, instead of rescanning from every starting point.
What it is
What is the sliding window pattern?
A sliding window is a contiguous segment of the input. You grow it on the right and shrink it on the left so it keeps a property, such as “no repeated characters” or “exactly k items”. Each element enters the window once and leaves once, so you never restart from each starting index.
- Fixed size. The window is always k wide. Add the new element, drop the old one.
- Variable size. The window grows until a rule breaks, then shrinks until it holds again.
Slide one step: add 3, drop 1 → 9
When to use it
How do you recognize a sliding window problem?
Read the statement for these signals before you reach for code.
Read the full recognition guide: How to recognize a sliding window problem
Phrases to watch for
- contiguous subarray or substring
- longest or shortest segment
- at most K
- without repeating
- window of size k
- maintain a property while expanding and shrinking
- optimize a range
- 1
The answer is a contiguous slice
The problem asks about a subarray or substring, so the elements must sit next to each other.
- 2
You want the longest or shortest segment
The goal is a length or a best sum over a segment that satisfies a rule.
- 3
One step in, one step out
You can update the answer by adding the new element and removing the one that left.
Looks similar, but isn’t
Subsequences, not slices
If elements may be skipped, a window will miss answers. Think Dynamic Programming.
A pair in a sorted list
Two ends closing in on a target is Two Pointers, not a moving slice.
Sum equals k with negatives
Shrinking stops being safe when values go negative. Try Prefix Sum with a Hash Map.
Worked example
How does it work on the longest substring without repeating characters?
Given a string, return the length of the longest stretch with no repeated character. It is a classic variable-size window, and one of the problems you can practice below.
function lengthOfLongestSubstring(s: string): number { const lastSeen = new Map<string, number>(); let left = 0; let best = 0; for (let right = 0; right < s.length; right++) { const ch = s[right]; const prev = lastSeen.get(ch); // A repeat inside the window: move left past it. if (prev !== undefined && prev >= left) { left = prev + 1; } lastSeen.set(ch, right); best = Math.max(best, right - left + 1); } return best;}The only place the window shrinks.
Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.
Complexity
- TimeO(n)
Each index enters the window once, and
leftnever moves back. - SpaceO(k)
kis the number of distinct characters stored in the map.
Fixed-size variant
When the width is a fixed k, drop the shrinking rule. Add nums[right], subtract nums[right - k], and keep the best total.
Why the map stores an index
Storing the last index lets left jump straight past a repeat in one move, instead of shrinking one character at a time.
Step by step on abcabcbb
- 1
Start with
left = 0and an emptylastSeenmap. Moverightone character at a time and record where each character was last seen.aL·Rbcabcbb - 2
rightreachescat index 2. The charactersa,bandcare all new, so the window grows toabcandbest = 3.aLbcRabcbb - 3
righthitsaat index 3. It was last seen at index 0, inside the window, soleftjumps to 1. The window isbca, still length 3.abLcaRbcbb - 4
bandcrepeat the same way.leftmoves to 2, then 3, and the window slides along ascab, thenabc.abcaLbcRbb - 5
At index 6,
bwas last seen at 4, soleftbecomes 5. At index 7 anotherb(seen at 6) pushesleftto 7. The window is now justb.abcabcbbL·R - 6
Return
best = 3.rightvisited each index once andleftonly ever moved forward, so the total work is O(n).abcabcbb
Common mistakes
What mistakes do people make with sliding window?
Restarting the window at every start index
Rescanning from each left end turns one pass into O(n²) and throws away work you already did.
InsteadKeep one window and move its ends forward. Update the state instead of rebuilding it.
Shrinking too far
Moving left past the repeat, or past the point the rule is satisfied again, can skip a longer valid window.
InsteadShrink only while the rule is broken, and stop the moment it holds again.
Trusting a stale lookup
A hash map can remember a character from before the window began. Using that index drags left backwards.
InsteadCompare the stored index with left first. Only an index inside the window counts.
Off-by-one on the length
Window length is right − left + 1. Dropping the +1 makes every answer one too small.
InsteadWrite the length formula once, and check it on a window of size 1.
Practice it in Algofily
Which Algofily problems train sliding window?
4 problems are tagged Sliding Window. They run from a fixed-width sum up to a hard covering window.
- Locked: opens after you create an account. Densest Block of keasySliding WindowYou have a list of readings and a block width k.Algofily 40Open problem
- Locked: opens after you create an account. Longest Distinct StretchmediumSliding Window · Hash MapA log line is a string.Algofily 40Open problem
- Locked: opens after you create an account. Budgeted Uniform StretchmediumSliding WindowYou may replace up to budget characters in a string.Algofily 40Open problem
- Locked: opens after you create an account. Shortest Covering WindowhardSliding Window · Hash MapFind the shortest contiguous slice of text that contains every character in need, including duplicates.Algofily 40Open problem
A lock means the problem opens after you create an account. Pair With Target is open to try without one.
Start Learning.
Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.