Sliding Window
Two pointers that move in the same direction to compute window-based answers in O(n).
Intro
Sliding window collapses the brute-force O(n²) subarray search into O(n) by reusing the work done at the previous position. You expand the right pointer to grow the window, and shrink the left pointer when the window stops being valid.
Key insight
The window represents 'the best answer ending at index right'. Whenever validity breaks, shrink from the left until it holds again.
Approach
- 1Initialise left = 0 and an aggregate (sum, character counts, distinct count, …).
- 2Iterate right from 0 to n-1, including arr[right] in the aggregate.
- 3While the window is invalid, drop arr[left] from the aggregate and increment left.
- 4After each step, update the answer using the current window (right - left + 1).
Example
s = "abcabcbb" → longest substring with all unique characters3 ("abc")- right=0..2 → window 'abc', size 3
- right=3 'a' duplicates → shrink until left=1, window 'bca'
- right=4 'b' duplicates → left=2, window 'cab' …
- max never exceeds 3.
Complexity
Time
O(n)
Space
O(k) for the auxiliary aggregate
Code
int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
Arrays.fill(last, -1);
int best = 0, left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (last[c] >= left) left = last[c] + 1;
last[c] = right;
best = Math.max(best, right - left + 1);
}
return best;
}def min_window_sum(arr, target):
left, total, best = 0, 0, float('inf')
for right, x in enumerate(arr):
total += x
while total >= target:
best = min(best, right - left + 1)
total -= arr[left]
left += 1
return 0 if best == float('inf') else best
Pitfalls
- Forgetting to subtract the leftmost element when shrinking the window.
- Using a HashMap when a 26- or 128-element array would do — slower in tight loops.
- Updating the answer outside the window-valid region (off-by-one).
Variants & follow-ups
- Longest substring with at most K distinct characters
- Permutation in string (LC 567)
- Find all anagrams in a string (LC 438)
Related reads
Pattern
Two Pointers
Two indices moving from opposite ends — turns sorted-array search problems into O(n).
Problem
Longest Substring Without Repeating Characters
Sliding window with a 'last seen' index — O(n), single pass.
Problem
Best Time to Buy and Sell Stock
Maximize profit with one buy and one sell. Track the minimum so far in a single pass.