Sliding window and two pointers are interview staples because they convert brute-force O(n^2) scans into O(n) passes.
Use them when a problem asks for:
- Longest or shortest subarray or substring
- Count of valid windows
- Pair conditions in sorted arrays
- In-place partitioning or deduplication
Pattern 1: Fixed-size sliding window
Use when window length k is fixed.
export function maxWindowSum(nums: number[], k: number): number {
if (k <= 0 || k > nums.length) throw new Error("invalid k");
let windowSum = 0;
for (let i = 0; i < k; i++) windowSum += nums[i]!;
let best = windowSum;
for (let right = k; right < nums.length; right++) {
windowSum += nums[right]!;
windowSum -= nums[right - k]!;
best = Math.max(best, windowSum);
}
return best;
}
Time is O(n), space is O(1).
Pattern 2: Variable-size sliding window
Use when condition depends on current window content, like:
- "Longest substring without repeating characters"
- "Smallest subarray with sum >= target"
Template idea:
- Expand right pointer
- While window invalid, move left pointer
- Update answer
Example: longest substring without repeating characters.
export function lengthOfLongestUniqueSubstring(s: string): number {
const seen = new Map<string, number>();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const char = s[right]!;
if (seen.has(char) && seen.get(char)! >= left) {
left = seen.get(char)! + 1;
}
seen.set(char, right);
best = Math.max(best, right - left + 1);
}
return best;
}
Pattern 3: Opposite-direction pointers
Use when array is sorted and you need pairs:
- Two-sum in sorted array
- Remove duplicates in place
- Container with most water
export function twoSumSorted(nums: number[], target: number): [number, number] | null {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const sum = nums[left]! + nums[right]!;
if (sum === target) return [left, right];
if (sum < target) left++;
else right--;
}
return null;
}
How to choose quickly in interviews
- Fixed
k-> fixed window - "At most k distinct" or "no duplicates" -> variable window + frequency map
- Sorted array + pair relation -> opposite pointers
- In-place array rewrite -> fast and slow pointers
Common mistakes
- Updating answer before shrinking invalid windows
- Forgetting to remove zero-count keys from frequency maps
- Moving wrong pointer in sorted pair problems
- Using window techniques when condition is not monotonic
Practice set
- Maximum sum subarray of size k
- Longest substring without repeating characters
- Minimum size subarray sum
- Longest repeating character replacement
- Two sum II (sorted)
- Container with most water
If the question asks for contiguous ranges, sliding window is usually the first thing to test.
