Sliding window technique for coding interviews, explained
The sliding window technique is one of the highest-return patterns to learn for a coding interview, because a single idea collapses a whole family of array and string problems from a slow nested loop into a fast single pass. The pattern: instead of re-examining every subarray from scratch, you keep a window — a contiguous range defined by two pointers — and slide it across the data, adding the new element on the right and removing the old one on the left, so each element is visited a constant number of times. Where a brute-force solution recomputes everything for every starting index at O(n²), the window reuses the work it already did and runs in O(n).
It is worth learning as a pattern, not a set of memorised solutions, because the recognition is the hard part: once you can spot the signal — a question about the longest or shortest contiguous subarray or substring that satisfies some condition — the implementation is almost always the same template with a different condition inside. This guide covers the core mechanic, the two templates (fixed-size and variable-size windows), the signals that tell you to reach for it, the problems it solves, and the follow-ups an interviewer uses to check you understand why the window is correct, not just that it passes.
Why the sliding window comes up in coding interviews
Interviewers love the sliding window because the brute-force answer is obvious and the efficient answer is not, so the problem cleanly separates candidates who can recognise structure from those who only pattern-match on keywords. You are asked for the longest substring without repeating characters, you reach for two nested loops, and the interviewer asks the question that is really the point: can you do it in one pass? That is the moment the window earns its place — and the moment a candidate who has only memorised solutions, rather than the pattern, gets stuck.
The interviewer rarely lets the brute-force answer stand. "That's O(n squared) — the array has a hundred million elements. Walk me through how you'd do it in a single pass, and convince me you never miss a valid window." That question — the correctness of the slide, not just its speed — is the one a memorised solution can never survive, and the one this pattern is really testing.
The rounds on Zynter are modelled on how the loop runs, not scraped from any candidate's recall. What matters for prep is the shape: you give a solution, and the next sentence out of the interviewer's mouth asks you to make it faster or to justify why it is correct.
What the interviewer is really testing
A coding answer is read on four dimensions, and the sliding window exercises all of them. Problem solving — did you recognise a contiguous-subarray problem and reach for a window instead of nested loops? Communication — can you say in one sentence what the window represents and why sliding it is correct? Technical execution — can you write the template cleanly, handling the shrink condition and the edge cases? Time management — did you get to O(n) without thrashing on off-by-one errors? Reading this guide teaches the pattern; it does not teach you to narrate the window while someone asks why it never misses a case.
The core mechanic: from O(n²) to O(n)
Start with why the window works. The brute force for "find the best contiguous subarray" tries every start, and for each start extends to every end — O(n²) subarrays. The insight is that as the window's right edge moves forward, you do not have to recompute the whole window: you update a running summary (a sum, a count, a character frequency map) incrementally, and when the window violates its condition you move the left edge forward to restore it. Each pointer only ever moves forward, so across the whole run each element is added once and removed once — 2n moves, which is O(n).
The variable-size window is the general template. The window grows by moving right, and shrinks by moving left whenever the condition is broken:
def longest_valid_window(s):
left = 0
state = {} # running summary of the window (e.g. char counts)
best = 0
for right in range(len(s)):
add(state, s[right]) # expand: include s[right]
while not valid(state): # shrink until the window is valid again
remove(state, s[left])
left += 1
best = max(best, right - left + 1) # window [left, right] is valid here
return best
The whole family of problems is this skeleton with a different state, valid(), and answer. Say that out loud in the interview — "this is a variable-size sliding window; I expand on the right, shrink from the left when it breaks, and track the best valid window" — and you have shown the pattern, not just a solution.
Fixed-size versus variable-size windows
There are two shapes of the pattern, and naming which one a problem needs is half the answer.
Fixed-size window. The window length k is given — "the maximum sum of any subarray of size k", "the average of every window of k days". You slide a window of constant width: add the entering element, remove the leaving element, and read the summary at each step. No shrink loop is needed because the size never changes.
def max_sum_fixed(nums, k):
window = sum(nums[:k])
best = window
for right in range(k, len(nums)):
window += nums[right] - nums[right - k] # add entering, drop leaving
best = max(best, window)
return best
Variable-size window. The window length is not given; you are asked for the longest or shortest window that satisfies a condition — "longest substring without repeating characters", "smallest subarray with a sum at least target". This is the expand-right / shrink-left template above. The condition drives the size.
The rule to say: fixed window when the size is given, variable window when you are optimising the size against a condition. Most interview sliding-window problems are the variable kind, which is why the expand/shrink template is the one to have automatic.
Coding
Coding · Arrays & strings
Solve a sliding-window problem out loud
How to recognise a sliding-window problem
The pattern lives behind a small set of signals. When a prompt has these shapes, reach for a window before you write a nested loop:
| The prompt says… | Reach for… |
|---|---|
| "longest / shortest contiguous subarray or substring" with a condition | variable-size window |
| "subarray / substring of size k" (fixed) | fixed-size window |
| "maximum / minimum sum, average, or count over a window" | window with a running sum/count |
| "without repeating characters" / "at most k distinct" | variable window with a frequency map |
| "smallest window containing all of X" | variable window that shrinks once valid |
The two words that matter most are contiguous and window-shaped condition. If the problem is about a subsequence (not contiguous) or needs a sorted pair, that is a different pattern — two pointers or a hash map — and reaching for a window there is the common mistake. Say the recognition out loud: "this asks for a contiguous window optimising a condition, so it is a sliding window."
Problems the sliding window solves
These are the canonical problems; practise them until the template is reflex, not memory:
- Longest substring without repeating characters — variable window with a set/last-seen map; shrink when a duplicate enters.
- Minimum size subarray sum — smallest window whose sum ≥ target; expand, then shrink while still valid.
- Longest substring with at most K distinct characters — variable window with a frequency map of size ≤ K.
- Maximum sum subarray of size K / maximum average — fixed window, add-and-drop.
- Permutation in string / find all anagrams — fixed window of the pattern's length, compare frequency maps.
- Fruit into baskets / longest subarray with a constraint — variable window with a bounded summary.
Each is the same two templates with a different state and valid(). Once you have solved three or four out loud, the next one is recognition plus the skeleton — which is exactly the muscle a timed round tests.
Coding
Coding · Longest substring
Narrate the expand/shrink window out loud
The follow-ups that decide a sliding-window question
The probes rhyme across every window problem. Master these and you can defend a window in any version of the question.
- "That's O(n squared) — can you do it in one pass?" → Yes: a sliding window, because each pointer only moves forward, so it is O(n). (problem solving)
- "Why does the window never miss a valid answer?" → Because every element enters once and leaves once, and the best valid window is checked at each right-step; no valid window is skipped. (communication)
- "When do you shrink the window?" → The moment the condition breaks — move left forward until it is valid again — for a variable window; a fixed window just slides. (technical execution)
- "What's the time and space complexity?" → O(n) time (2n pointer moves); space is O(1) or O(k) for the window's summary, not O(n). (technical execution)
- "What breaks your solution — negative numbers, empty input, k larger than the array?" → Name the edge cases and how the template handles each. (problem solving)
Each maps to a debrief dimension. Reading them teaches the answers; it does not teach you to deliver them while someone interrupts with "prove it is correct" — that only comes from saying them out loud.
How to prepare: a short plan
You do not need a hundred problems. You need the two templates automatic and the recognition instant, so a contiguous-subarray prompt triggers the window without thinking.
- Day 1: Learn why the window is O(n) and write both templates — fixed-size add-and-drop, and variable-size expand/shrink — from memory until they are reflex.
- Day 2: Drill recognition on ten prompts: for each, say "window or not, fixed or variable, what is the state and the valid condition" before writing a line. This is the skill the round tests.
- Day 3: Solve four canonical problems out loud, timed, narrating the window and answering "why is it correct" as you go, with someone (or something) pushing for the one-pass solution.
This pattern is one row of the broader coding interview patterns — once the sliding window is automatic, the two-pointer and hash-map patterns next to it fall quickly.
Frequently asked questions
What is the sliding window technique?
The sliding window technique solves problems about a contiguous range of an array or string by maintaining a window — a range defined by a left and right pointer — and moving it across the data instead of re-examining every possible subarray. As the right pointer expands the window to include a new element, you update a running summary (a sum, a count, a frequency map) incrementally, and when the window breaks its condition you move the left pointer forward to restore it. Because each pointer only moves forward, every element is added and removed once, which turns an O(n²) brute force into an O(n) single pass.
When should I use a sliding window in an interview?
Reach for a sliding window when the problem asks about a contiguous subarray or substring and optimises some condition over it — the longest or shortest range, a maximum or minimum sum, a window of a fixed size k, "without repeating characters", or "at most k distinct". The keyword that matters most is contiguous: if the elements must be adjacent, a window usually applies. If the problem is about a non-contiguous subsequence, a sorted pair, or needs elements from both ends, that is a different pattern — two pointers or hashing — and a window is the wrong tool there.
What is the difference between a fixed-size and a variable-size window?
A fixed-size window has a length k that the problem gives you, so you slide a constant-width window across the array, adding the entering element and dropping the leaving one at each step — no shrinking is needed. A variable-size window does not have a given length; you are asked for the longest or shortest window that satisfies a condition, so you expand the right edge to grow the window and shrink the left edge whenever the condition is violated, letting the condition decide the size. Most interview sliding-window problems are the variable kind, so the expand-right / shrink-left template is the one to have automatic.
What is the time complexity of a sliding window?
A sliding window runs in O(n) time, because the left and right pointers each move forward across the array at most once, giving at most 2n pointer moves in total — far better than the O(n²) of checking every subarray with nested loops. The space complexity is usually O(1) for a numeric summary like a running sum, or O(k) when the window keeps a frequency map bounded by the number of distinct elements or the window size. That O(n) time with small space is exactly why the pattern is such a high-return thing to learn.
Is the sliding window the same as two pointers?
They are related but not identical. A sliding window is a specific use of two pointers where both pointers move in the same direction and define a contiguous range that grows and shrinks — used for contiguous subarray and substring problems. The broader two-pointer pattern also includes pointers that move toward each other from both ends of a sorted array (for pair-sum problems) or a fast and slow pointer (for linked-list cycles). So the sliding window is one branch of the two-pointer family, specialised for maintaining a contiguous window.
How do I practise coding interviews out loud?
Reading about the sliding window is not the same as narrating one while an interviewer asks you to prove it is correct. On Zynter, the Coding track runs live voice rounds modelled on how real coding loops run — you solve in a real editor where your code runs, and a voice interviewer pushes with the follow-ups above one at a time ("that's O(n squared) — one pass?", "why does it never miss a window?"), then gives you a debrief on problem solving, communication, technical execution and time management. The score is a practice signal, not a hiring decision.
Practise it on Zynter
You can recite the template. The round is won on narrating the window out loud under a clock.
Pick a Coding round, solve a sliding-window problem in a real editor, and defend it out loud to a voice interviewer that keeps asking "that's O(n squared) — can you do it in one pass?" and "why does your window never miss a valid answer?" — then read the debrief. Zynter.ai is on-demand mock interviews modelled on real company loops, with 150+ rounds across 20 companies including the Coding track (Sep 2026).




Top comments (0)