STOP 04 · LINEAR STRUCTURES
Two Pointers and Sliding Windows
Variable-size sliding window O(n) time · O(Σ) space
- Learn first
- Leads to
- No later stop builds on it.
- How often asked
- asked by 19 companies · in 32 reportsTikTok / ByteDance 5, Amazon 3, Meta 3, Microsoft 3, Bloomberg 2
Warm up with this one
LC 125Valid PalindromeStuck? Peek at the approach
Skip nonalphanumeric characters, normalize case, and compare inward from both ends.
Key points
- The right end advances every step and the left end moves only while the window is invalid; both only go forward, so the total is O(n).
- For the longest window, update the answer after shrinking; for the shortest, update it inside the shrink loop while the window is still valid.
- On sorted arrays use opposite-end pointers for pair sums, dedupe and reversal; use fast/slow pointers for cycles and midpoints.
Common pitfalls
- Forgetting to decrement the count of the element leaving the window desynchronises the window state.
- With negative numbers "shrink when the sum exceeds k" is no longer monotonic and the window breaks; use prefix sums instead.
- "Exactly k" is awkward to slide directly; compute at-most(k) minus at-most(k-1).
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Two pointers · pair sum in a sorted array
Find two numbers that add up to 14
Try your own input
- Target
- 14
- left
- 0
- right
- 6
- Sum
- 16
The array is sorted. left starts at the smallest value, right at the largest.
InvariantIf a pair exists it lies inside [left, right]: a skipped value cannot pair with anything left to reach the target.
Sliding window · no repeated characters
Input: abcabcbb
Try your own input
- left
- 0
- right
- -1
- Window
- 0
- Longest
- 0
Start with an empty window; find the longest substring without a repeated character.
InvariantAfter each new right character the window holds distinct characters; left only moves right.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 125, with it.
Python
from collections import defaultdict
def longest_unique(s: str) -> int:
"""Length of the longest substring without repeated characters."""
cnt = defaultdict(int) # counts inside the window s[left:right+1]
left = best = 0
for right, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1: # shrink until the window is valid again
cnt[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return bestC++
// Length of the longest substring without repeated characters.
int longestUnique(const string& s) {
unordered_map<char, int> cnt; // counts inside the window s[left..right]
int left = 0, best = 0;
for (int right = 0; right < (int)s.size(); right++) {
char c = s[right];
cnt[c]++;
while (cnt[c] > 1) cnt[s[left++]]--; // shrink until the window is valid again
best = max(best, right - left + 1);
}
return best;
}Java
class Solution {
// Length of the longest substring without repeated characters.
int longestUnique(String s) {
Map<Character, Integer> cnt = new HashMap<>(); // counts inside the window s[left..right]
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
cnt.merge(c, 1, Integer::sum);
while (cnt.get(c) > 1) cnt.merge(s.charAt(left++), -1, Integer::sum); // shrink
best = Math.max(best, right - left + 1);
}
return best;
}
}Go
// longestUnique returns the length of the longest substring without repeated bytes.
func longestUnique(s string) int {
cnt := map[byte]int{} // counts inside the window s[left:right+1]
left, best := 0, 0
for right := 0; right < len(s); right++ {
c := s[right]
cnt[c]++
for cnt[c] > 1 { // shrink until the window is valid again
cnt[s[left]]--
left++
}
best = max(best, right-left+1)
}
return best
}Common variants
Problems at this stop also need the 3 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Fixed-size sliding windowO(n) time · O(1) space
When the window length k is fixed (the most of something in a length-k substring, whether a permutation occurs): each element that enters on the right pushes out the one at i - k, and answers count only once the window holds k. LC 1456, LC 438 (Find All Anagrams in a String) and LC 567 (Permutation in String) have this shape.
Python
def max_vowels(s: str, k: int) -> int:
"""Most vowels in any length-k substring (LC 1456)."""
vowels = set("aeiou")
cur = best = 0
for i, c in enumerate(s):
cur += c in vowels # c enters the window
if i >= k:
cur -= s[i - k] in vowels # s[i - k] leaves: the window is s[i-k+1..i]
if i >= k - 1: # only full windows count
best = max(best, cur)
return bestC++
// Most vowels in any length-k substring (LC 1456).
int maxVowels(const string& s, int k) {
auto vowel = [](char c) { return string("aeiou").find(c) != string::npos; };
int cur = 0, best = 0;
for (int i = 0; i < (int)s.size(); i++) {
cur += vowel(s[i]); // s[i] enters the window
if (i >= k) cur -= vowel(s[i - k]); // s[i - k] leaves: the window is s[i-k+1..i]
if (i >= k - 1) best = max(best, cur); // only full windows count
}
return best;
}Java
class Solution {
// Most vowels in any length-k substring (LC 1456).
int maxVowels(String s, int k) {
int cur = 0, best = 0;
for (int i = 0; i < s.length(); i++) {
if (vowel(s.charAt(i))) cur++; // s[i] enters the window
if (i >= k && vowel(s.charAt(i - k))) cur--; // s[i - k] leaves: the window is s[i-k+1..i]
if (i >= k - 1) best = Math.max(best, cur); // only full windows count
}
return best;
}
private boolean vowel(char c) {
return "aeiou".indexOf(c) >= 0;
}
}Go
import "strings"
// maxVowels returns the most vowels in any length-k substring (LC 1456).
func maxVowels(s string, k int) int {
vowel := func(c byte) int {
if strings.IndexByte("aeiou", c) >= 0 {
return 1
}
return 0
}
cur, best := 0, 0
for i := 0; i < len(s); i++ {
cur += vowel(s[i]) // s[i] enters the window
if i >= k {
cur -= vowel(s[i-k]) // s[i - k] leaves: the window is s[i-k+1..i]
}
if i >= k-1 { // only full windows count
best = max(best, cur)
}
}
return best
}Two pointers from both ends: move the shorter sideO(n) time · O(1) space
When the answer depends on both ends and the worse end provably cannot take part in a better answer, close in from both ends. LC 11 (Container With Most Water) moves the shorter wall each time; LC 167 and LC 15 (3Sum) move by comparing the sum on a sorted array.
Python
def max_area(height: list[int]) -> int:
"""Most water two walls can hold (LC 11)."""
lo, hi = 0, len(height) - 1
best = 0
while lo < hi:
best = max(best, (hi - lo) * min(height[lo], height[hi]))
if height[lo] < height[hi]: # the shorter wall caps every narrower pair it is in
lo += 1
else:
hi -= 1
return bestC++
// Most water two walls can hold (LC 11).
long long maxArea(const vector<int>& height) {
int lo = 0, hi = (int)height.size() - 1;
long long best = 0;
while (lo < hi) {
best = max(best, (long long)(hi - lo) * min(height[lo], height[hi]));
if (height[lo] < height[hi]) lo++; // the shorter wall caps every narrower pair it is in
else hi--;
}
return best;
}Java
class Solution {
// Most water two walls can hold (LC 11).
long maxArea(int[] height) {
int lo = 0, hi = height.length - 1;
long best = 0;
while (lo < hi) {
best = Math.max(best, (long) (hi - lo) * Math.min(height[lo], height[hi]));
if (height[lo] < height[hi]) lo++; // the shorter wall caps every narrower pair it is in
else hi--;
}
return best;
}
}Go
// maxArea returns the most water two walls can hold (LC 11).
func maxArea(height []int) int {
lo, hi := 0, len(height)-1
best := 0
for lo < hi {
best = max(best, (hi-lo)*min(height[lo], height[hi]))
if height[lo] < height[hi] { // the shorter wall caps every narrower pair it is in
lo++
} else {
hi--
}
}
return best
}Exactly K = at most K − at most K−1O(n) time · O(n) space
Counting subarrays with exactly K distinct values (or exactly K odd numbers, or sum exactly K) does not shrink monotonically, but at most K does: at each right end, right - left + 1 valid windows end there. Subtract two such counts to get exactly K. LC 992, LC 930 and LC 1248 work this way.
Python
from collections import defaultdict
def subarrays_with_k_distinct(nums: list[int], k: int) -> int:
"""Subarrays with exactly k distinct values (LC 992)."""
def at_most(k: int) -> int: # subarrays with at most k distinct values
cnt = defaultdict(int)
left = total = 0
for right, x in enumerate(nums):
cnt[x] += 1
if cnt[x] == 1:
k -= 1
while k < 0: # one distinct value too many: shrink from the left
cnt[nums[left]] -= 1
if cnt[nums[left]] == 0:
k += 1
left += 1
total += right - left + 1 # windows that end at right and start at or after left
return total
return at_most(k) - at_most(k - 1)C++
// Subarrays with exactly k distinct values (LC 992).
long long subarraysWithKDistinct(const vector<int>& nums, int k) {
auto atMost = [&](int k) { // subarrays with at most k distinct values
unordered_map<int, int> cnt;
long long total = 0;
for (int left = 0, right = 0; right < (int)nums.size(); right++) {
if (++cnt[nums[right]] == 1) k--;
while (k < 0) // one distinct value too many: shrink from the left
if (--cnt[nums[left++]] == 0) k++;
total += right - left + 1; // windows that end at right and start at or after left
}
return total;
};
return atMost(k) - atMost(k - 1);
}Java
class Solution {
// Subarrays with exactly k distinct values (LC 992).
long subarraysWithKDistinct(int[] nums, int k) {
return atMost(nums, k) - atMost(nums, k - 1);
}
// Subarrays with at most k distinct values.
private long atMost(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
long total = 0;
for (int left = 0, right = 0; right < nums.length; right++) {
if (cnt.merge(nums[right], 1, Integer::sum) == 1) k--;
while (k < 0) // one distinct value too many: shrink from the left
if (cnt.merge(nums[left++], -1, Integer::sum) == 0) k++;
total += right - left + 1; // windows that end at right and start at or after left
}
return total;
}
}Go
// subarraysWithKDistinct counts the subarrays with exactly k distinct values (LC 992).
func subarraysWithKDistinct(nums []int, k int) int {
atMost := func(k int) int { // subarrays with at most k distinct values
cnt := map[int]int{}
left, total := 0, 0
for right, x := range nums {
cnt[x]++
if cnt[x] == 1 {
k--
}
for k < 0 { // one distinct value too many: shrink from the left
cnt[nums[left]]--
if cnt[nums[left]] == 0 {
k++
}
left++
}
total += right - left + 1 // windows that end at right and start at or after left
}
return total
}
return atMost(k) - atMost(k-1)
}Why it works
- Shrinking from the left never loses an answer: if [l, r] is invalid, every window that still starts at l and ends at r or later is invalid too, so l can move right for good.
- This needs validity to be monotone under containment: if a window is valid, every sub-window is valid too. Subarray sums with negative numbers break this, which is why they need prefix sums instead.
- Each of l and r only moves forward, at most n steps apiece, so the inner while runs O(n) times in total, not O(n²).
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
我用可变滑动窗口:右端每一步都扩张,窗口一旦不合法就移动左端直到恢复合法,在合适的位置更新答案。正确性靠单调性:一个窗口不合法时,同一个左端配更远的右端也不会合法,所以左端可以放心右移、不会漏解。两个指针都只往前走,总共 O(n)。如果数组里有负数导致这种单调性不成立,我会换成前缀和加哈希表。I use a variable-size sliding window: the right end grows every step, and while the window is invalid the left end moves forward until it is valid again. It is correct because validity is monotone: if a window is invalid, keeping the same left end with a farther right end cannot fix it, so moving the left end never skips an answer. Both pointers only move forward, so the total work is O(n). If negative numbers break that monotonicity, I switch to prefix sums with a hash map.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
Practice by stage
This stop's 38 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 5
| # | Problem | Approach | Rating |
|---|---|---|---|
| 125 | Valid Palindrome | Skip nonalphanumeric characters, normalize case, and compare inward from both ends. | |
| 167 | Two Sum II - Input Array Is Sorted | Use sorted order to move the left and right pointers, eliminating impossible pairs at each step. | |
| 977 | Squares of a Sorted Array | The largest square in a sorted array lies at an end, so fill the output from the back. | |
| 1456 | Maximum Number of Vowels in a Substring of Given Length | Update a fixed-length window's count by adding the incoming character and removing the outgoing one. | |
| 2090 | K Radius Subarray Averages | Translate radius averages into fixed-length windows and identify positions with insufficient elements at either end. |
Core 26
| # | Problem | Approach | Rating |
|---|---|---|---|
| 11 | Container With Most Water | Prove that moving the shorter side is the only way to improve the container area without enumerating all endpoint pairs. | |
| 42 | Trapping Rain Water | Determine trapped water from left and right maximum heights; compare prefix/suffix preprocessing, two pointers, and a monotonic stack, explaining why the lower boundary moves. | |
| 15 | 3Sum | Fix one element, then use inward-moving pointers and remove duplicates at every level. | |
| 16 | 3Sum Closest | Maintain the sum closest to the target, separating pointer movement from updating the best answer. | |
| 680 | Valid Palindrome II | At the first mismatch, try deleting either endpoint; no other deletion position needs to be considered. | |
| 844 | Backspace String Compare | Count backspaces while scanning backward, skipping deleted characters in constant extra space. | |
| 3 | Longest Substring Without Repeating Characters | Maintain a window of distinct characters and advance its left boundary without ever moving it backward. | |
| 209 | Minimum Size Subarray Sum | Use positivity to shrink a window that reaches the target and find its minimum length. | |
| 438 | Find All Anagrams in a String | Use frequency differences or matched counts to identify anagrams in each fixed-length window. | |
| 567 | Permutation in String | Reduce permutation inclusion to matching fixed-length frequency counts, stopping at the first match. | |
| 1052 | Grumpy Bookstore Owner | Separate guaranteed satisfaction from the optional window's extra benefit to avoid double-counting customers. | |
| 159 | Longest Substring with At Most Two Distinct Characters 🔒 | Maintain a window with at most two character types, removing a type when its count reaches zero. | |
| 340 | Longest Substring with At Most K Distinct Characters 🔒 | Generalize from at most two types to at most k, keeping frequencies and the distinct-type count consistent. | |
| 904 | Fruit Into Baskets | Model the two-fruit restriction as the longest contiguous window containing at most two element types. | |
| 424 | Longest Repeating Character Replacement | Compute replacement demand as window length minus maximum frequency, and understand the historical-maximum optimization. | |
| 1004 | Max Consecutive Ones III | Treat the number of zeros that can be flipped as a budget and maintain the longest affordable window. | |
| 1493 | Longest Subarray of 1's After Deleting One Element | Model mandatory deletion as a window containing at most one zero, with special care for an all-ones array. | |
| 1208 | Get Equal Substrings Within Budget | Convert positionwise string differences into nonnegative costs and maintain the window's total budget. | |
| 713 | Subarray Product Less Than K | Use the monotonicity of positive-integer products to count all valid suffixes of a window. | |
| 1658 | Minimum Operations to Reduce X to Zero | Turn removals from both ends into retaining the longest middle subarray with a target sum. | |
| 1838 | Frequency of the Most Frequent Element | After sorting, compute the cost of equalizing a window from its length and sum, then find the largest feasible window. | |
| 1234 | Replace the Substring for Balanced String | Maintain frequencies outside the replacement window and express validity as constraints on those external counts. | |
| 1358 | Number of Substrings Containing All Three Characters | Once a window covers all three character types, count its valid extensions in bulk. | |
| 2024 | Maximize the Confusion of an Exam | Consider making all answers each of the two possible values, using changes as the window budget. | |
| 2516 | Take K of Each Character From Left and Right | Convert taking characters from both ends into frequency limits on the middle substring that can remain. | |
| 2302 | Count Subarrays With Score Less Than K | Maintain the score as window sum times length and count valid suffixes in bulk. |
Advanced 7
| # | Problem | Approach | Rating |
|---|---|---|---|
| 18 | 4Sum | Extend fixed-element enumeration with two pointers, handling duplicates, pruning, and integer overflow. | |
| 76 | Minimum Window Substring | Distinguish satisfying character types from satisfying their full multiplicities when shrinking the minimum covering window. | |
| 30 | Substring with Concatenation of All Words | Slide in groups aligned by word length, maintaining a multiset of words rather than character frequencies. | |
| 395 | Longest Substring with At Least K Repeating Characters | Enumerate the target number of character types or divide around low-frequency characters to handle a nonmonotonic window condition. | |
| 992 | Subarrays with K Different Integers | Subtract the count with at most k minus one distinct values from the count with at most k to obtain exactly k. | |
| 1438 | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Maintain window extrema with two monotonic deques and adjust the left boundary to satisfy the difference limit. | |
| 2537 | Count the Number of Good Subarrays | Update the number of equal pairs incrementally when inserting or removing an element, and count windows reaching the threshold. |
OA questions on this topic 145
- Longest Subarray With Value Frequency > ThresholdMeta
- Find Pair Closest to K (for E5 :)Meta
- Max Consecutive Ones III (for E5 :)Meta
- Merge Three Sorted ArraysMeta
- Sliding Window AverageMeta
- Combine Two Vectors of Intervals (MLE)Meta
- Enumerating Narrative SectionsMeta
- Self-Sufficient SubstringAmazon
- Find Similarities (Password Subsequence)Amazon
- Find Maximum PackagesAmazon
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.