cswork / templatesOpen the Line 500 list

STOP 04 · LINEAR STRUCTURES

Two Pointers and Sliding Windows

Variable-size sliding window O(n) time · O(Σ) space

Contest ratings Rating 1130–Rating 2210· median Rating 1646(19 of 38 problems rated by zerotrac)

Open the Line 500 list · stop 04 · 38 problems
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 PalindromeEasy
Stuck? Peek at the approach

Skip nonalphanumeric characters, normalize case, and compare inward from both ends.

Key points

  1. 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).
  2. For the longest window, update the answer after shrinking; for the shortest, update it inside the shrink loop while the window is still valid.
  3. 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.

Interactive demo · step by step

Two pointers · pair sum in a sorted array

Find two numbers that add up to 14

Try your own input
1L·0
31
42
63
84
115
15R·6
CurrentDiscovered / computedAnswer
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.

Interactive demo · step by step

Sliding window · no repeated characters

Input: abcabcbb

Try your own input
a0
b1
c2
a3
b4
c5
b6
b7
CurrentDiscovered / computedAnswer
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 best
C++
// 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 best
C++
// 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 best
C++
// 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

  1. 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.
  2. 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.
  3. 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)。如果数组里有负数导致这种单调性不成立,我会换成前缀和加哈希表。
English
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.

Key points you covered (0 of 3)
How well did you know it?

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

4 questions
  1. The opposite-ends two-pointer search for a pair summing to target (move left up when the sum is too small, right down when too big) is correct only when:
  2. For "longest subarray with sum at most K", the usual sliding window grows the right end one step at a time and shrinks the left end while the sum exceeds K. What does it rely on?
  3. a holds non-negative integers and k >= 0. What is the time complexity (n = len(a))?
    def longest(a, k):
        best = lo = total = 0
        for hi in range(len(a)):
            total += a[hi]
            while total > k:
                total -= a[lo]
                lo += 1
            best = max(best, hi - lo + 1)
        return best
  4. What is the time complexity of this code (n = len(a), tightest bound)?
    def count_pairs(a, t):
        a.sort()
        i, j, count = 0, len(a) - 1, 0
        while i < j:
            if a[i] + a[j] <= t:
                count += j - i
                i += 1
            else:
                j -= 1
        return count

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

#ProblemApproachRating
125Valid PalindromeSkip nonalphanumeric characters, normalize case, and compare inward from both ends.
167Two Sum II - Input Array Is SortedUse sorted order to move the left and right pointers, eliminating impossible pairs at each step.
977Squares of a Sorted ArrayThe largest square in a sorted array lies at an end, so fill the output from the back.Rating 1130
1456Maximum Number of Vowels in a Substring of Given LengthUpdate a fixed-length window's count by adding the incoming character and removing the outgoing one.Rating 1263
2090K Radius Subarray AveragesTranslate radius averages into fixed-length windows and identify positions with insufficient elements at either end.Rating 1358

Core 26

#ProblemApproachRating
11Container With Most WaterProve that moving the shorter side is the only way to improve the container area without enumerating all endpoint pairs.
42Trapping Rain WaterDetermine trapped water from left and right maximum heights; compare prefix/suffix preprocessing, two pointers, and a monotonic stack, explaining why the lower boundary moves.
153SumFix one element, then use inward-moving pointers and remove duplicates at every level.
163Sum ClosestMaintain the sum closest to the target, separating pointer movement from updating the best answer.
680Valid Palindrome IIAt the first mismatch, try deleting either endpoint; no other deletion position needs to be considered.
844Backspace String CompareCount backspaces while scanning backward, skipping deleted characters in constant extra space.Rating 1228
3Longest Substring Without Repeating CharactersMaintain a window of distinct characters and advance its left boundary without ever moving it backward.
209Minimum Size Subarray SumUse positivity to shrink a window that reaches the target and find its minimum length.
438Find All Anagrams in a StringUse frequency differences or matched counts to identify anagrams in each fixed-length window.
567Permutation in StringReduce permutation inclusion to matching fixed-length frequency counts, stopping at the first match.
1052Grumpy Bookstore OwnerSeparate guaranteed satisfaction from the optional window's extra benefit to avoid double-counting customers.Rating 1418
159Longest Substring with At Most Two Distinct Characters 🔒Maintain a window with at most two character types, removing a type when its count reaches zero.
340Longest 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.
904Fruit Into BasketsModel the two-fruit restriction as the longest contiguous window containing at most two element types.Rating 1516
424Longest Repeating Character ReplacementCompute replacement demand as window length minus maximum frequency, and understand the historical-maximum optimization.
1004Max Consecutive Ones IIITreat the number of zeros that can be flipped as a budget and maintain the longest affordable window.Rating 1656
1493Longest Subarray of 1's After Deleting One ElementModel mandatory deletion as a window containing at most one zero, with special care for an all-ones array.Rating 1423
1208Get Equal Substrings Within BudgetConvert positionwise string differences into nonnegative costs and maintain the window's total budget.Rating 1497
713Subarray Product Less Than KUse the monotonicity of positive-integer products to count all valid suffixes of a window.
1658Minimum Operations to Reduce X to ZeroTurn removals from both ends into retaining the longest middle subarray with a target sum.Rating 1817
1838Frequency of the Most Frequent ElementAfter sorting, compute the cost of equalizing a window from its length and sum, then find the largest feasible window.Rating 1876
1234Replace the Substring for Balanced StringMaintain frequencies outside the replacement window and express validity as constraints on those external counts.Rating 1878
1358Number of Substrings Containing All Three CharactersOnce a window covers all three character types, count its valid extensions in bulk.Rating 1646
2024Maximize the Confusion of an ExamConsider making all answers each of the two possible values, using changes as the window budget.Rating 1643
2516Take K of Each Character From Left and RightConvert taking characters from both ends into frequency limits on the middle substring that can remain.Rating 1948
2302Count Subarrays With Score Less Than KMaintain the score as window sum times length and count valid suffixes in bulk.Rating 1808

Advanced 7

#ProblemApproachRating
184SumExtend fixed-element enumeration with two pointers, handling duplicates, pruning, and integer overflow.
76Minimum Window SubstringDistinguish satisfying character types from satisfying their full multiplicities when shrinking the minimum covering window.
30Substring with Concatenation of All WordsSlide in groups aligned by word length, maintaining a multiset of words rather than character frequencies.
395Longest Substring with At Least K Repeating CharactersEnumerate the target number of character types or divide around low-frequency characters to handle a nonmonotonic window condition.
992Subarrays with K Different IntegersSubtract the count with at most k minus one distinct values from the count with at most k to obtain exactly k.Rating 2210
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMaintain window extrema with two monotonic deques and adjust the left boundary to satisfy the difference limit.Rating 1672
2537Count the Number of Good SubarraysUpdate the number of equal pairs incrementally when inserting or removing an element, and count windows reaching the threshold.Rating 1892

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.