I have been on both sides of the technical interview table, mostly as the candidate. The sliding window technique appears constantly, and it separates candidates who have internalized a pattern from candidates who are trying to derive the solution from scratch under pressure. The former finishes early and explains their thinking. The latter runs out of time. Here is how to get to the former position.
What the Pattern Actually Is
Sliding window is an optimization for problems involving contiguous sequences: subarrays or substrings. The naive approach to most of these problems is a nested loop that re-examines overlapping elements on every iteration, giving O(n squared) time. The sliding window avoids that by maintaining a range with two pointers and updating state incrementally as the range moves. Most problems drop to O(n).
There are two variants. Fixed-size windows: the window length is given to you. Dynamic windows: you expand and shrink based on a constraint. Identifying which variant you are dealing with is the first decision in any interview problem that fits this pattern.
When to Reach for This Pattern
- The problem involves a contiguous subarray or substring
- You are asked to find a maximum, minimum, or aggregate over all windows of a given size
- You are looking for the longest or shortest substring satisfying a constraint
- The brute-force solution has nested loops iterating over the same array or string
- The problem mentions a 'window', 'range', or 'consecutive' elements
Fixed Window: Maximum Sum Subarray of Size K
This is the entry point for the pattern. Given an array of integers and a number k, find the maximum sum of any contiguous subarray of length k. The naive approach sums k elements for every starting position: O(n times k). The sliding window adds the incoming element and removes the outgoing one, maintaining a running sum: O(n).
function maxSumSubarray(nums: number[], k: number): number {
if (nums.length < k) return 0;
// Build the first window
let windowSum = 0;
for (let i = 0; i < k; i++) {
windowSum += nums[i];
}
let maxSum = windowSum;
// Slide the window: add incoming, subtract outgoing
for (let i = k; i < nums.length; i++) {
windowSum += nums[i] - nums[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
console.log(maxSumSubarray([2, 1, 5, 1, 3, 2], 3)); // 9 (indices 2-4: 5+1+3)
console.log(maxSumSubarray([2, 3, 4, 1, 5], 2)); // 7 (3+4)The key operation is windowSum += nums[i] - nums[i - k]. You are not recalculating from scratch. You are sliding: add the new right element, drop the old left element. That one line is the entire insight of the fixed window.
One line in that code is a decision, not a detail. Returning 0 when the array is shorter than k hands back a value a real window could also produce, so the caller cannot tell 'no valid window' apart from 'the best window sums to zero'. I return 0 here to keep the example short. In an interview, say that out loud and pick deliberately: throw on invalid input, return null, or ask the interviewer what the contract should be. Noticing that a sentinel collides with a legitimate answer is the kind of thing they are listening for.
Dynamic Window: Longest Substring Without Repeating Characters
Dynamic windows require deciding when to shrink. In this problem the constraint is uniqueness: every character in the window must appear once. Expand the right pointer freely. When a duplicate enters the window, advance the left pointer until the duplicate is gone.
function lengthOfLongestUniqueSubstring(s: string): number {
const lastSeen = new Map<string, number>();
let left = 0;
let maxLength = 0;
for (let right = 0; right < s.length; right++) {
const char = s[right];
// If we've seen this char and it's inside the current window, jump left past it
if (lastSeen.has(char) && lastSeen.get(char)! >= left) {
left = lastSeen.get(char)! + 1;
}
lastSeen.set(char, right);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
console.log(lengthOfLongestUniqueSubstring('abcabcbb')); // 3 (abc)
console.log(lengthOfLongestUniqueSubstring('pwwkew')); // 3 (wke)Storing the last seen index rather than deleting map entries lets left jump straight to the correct position instead of stepping one character at a time. Be precise about what that buys you, because an interviewer will check. Both versions are O(n). In the step-one-at-a-time version the left pointer still moves at most n times across the whole loop, so the total work is linear either way. The jump saves map operations and a constant factor, not a complexity class.
The Reusable Template
Most dynamic window problems follow the same structure. Internalizing this template means you spend interview time on the problem-specific logic, not on scaffolding you have solved before.
function dynamicWindowTemplate(input: string | number[]): number {
let left = 0;
let result = 0;
const windowState = new Map<string | number, number>();
for (let right = 0; right < input.length; right++) {
const incoming = input[right];
// 1. Add incoming element to window state
windowState.set(incoming, (windowState.get(incoming) ?? 0) + 1);
// 2. Shrink window while constraint is violated
while (/* window constraint violated */ false) {
const outgoing = input[left];
const count = windowState.get(outgoing)! - 1;
if (count === 0) {
windowState.delete(outgoing);
} else {
windowState.set(outgoing, count);
}
left++;
}
// 3. Update result with current valid window
result = Math.max(result, right - left + 1);
}
return result;
}Recognizing the Pattern in an Interview
- Does the problem say 'subarray', 'substring', or 'contiguous'? Sliding window is the candidate pattern.
- Is k given? Fixed window. Is there a constraint to satisfy? Dynamic window.
- Does a brute-force solution require nested loops over the same data? You are looking at O(n squared) and sliding window will fix it.
- Can you describe the problem as: find the optimal range satisfying some condition? That is a sliding window problem.
In a whiteboard interview, naming the pattern out loud before writing code signals pattern recognition. That is one of the most valued signals an interviewer looks for.
Practice the fixed-window max sum and the dynamic longest-unique-substring problems until they feel mechanical. Those two cover the two structural variants. Every other sliding window problem you encounter in an interview is a variation on one of them. Once the template is internalized, the interview time goes toward the constraint-specific logic, which is the part that actually tests problem-solving ability.
References
- LeetCode. Sliding Window Problems. https://leetcode.com/tag/sliding-window/
- GeeksforGeeks. Sliding Window Technique. https://www.geeksforgeeks.org/window-sliding-technique/
- MDN Web Docs. JavaScript Array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array