Notes
All notes

Two Pointers and Sliding Window (DSA #27)

Most “find a subarray or substring” problems have an \(O(n^2)\) brute force that checks every start and end. The insight behind two pointers and sliding windows is that you rarely need to restart: as one boundary moves forward, the other only moves forward too, so a two-level loop collapses into a single pass. These two sibling techniques cover a huge fraction of array and string interview questions.

This chapter covers the three pointer layouts — converging, same-direction, and the sliding window — with the problems they solve.

Layout 1: converging pointers

Start one pointer at each end and move them toward each other. Use when the array is sorted and you are looking for a pair or a partition.

Two-sum on a sorted array: if the sum is too small, the only way to increase it is to move the left pointer right; if too large, move the right pointer left.

def two_sum_sorted(a, target):
    l, r = 0, len(a) - 1
    while l < r:
        s = a[l] + a[r]
        if s == target:
            return [l, r]
        if s < target:
            l += 1                 # need a larger sum
        else:
            r -= 1                 # need a smaller sum
    return []

The unsorted version needs a hash map (Chapter 6); sorting first enables the two-pointer \(O(n)\) scan at the cost of \(O(n \log n)\).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.62cm, font=\small\bfseries},
  a/.style={->, thick}]
  \foreach \v [count=\i from 0] in {1,3,5,7,9,11} { \node[c, fill=blue!8] at (\i*0.7,0) {\v}; }
  \draw[->, thick, green!50!black] (0,-0.55) -- (0,-0.1) node[below, font=\scriptsize, pos=0] {l};
  \draw[->, thick, orange!75!black] (3.5,-0.55) -- (3.5,-0.1) node[below, font=\scriptsize, pos=0] {r};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.8,-0.9) {sum too small -> move l right; too large -> move r left};
\end{tikzpicture}

Container with most water and trapping rain water use the same converging pointers. The companion note Trapping Rain Water derives the water formula and walks the pointers.

def max_area(heights):
    l, r, best = 0, len(heights) - 1, 0
    while l < r:
        best = max(best, (r - l) * min(heights[l], heights[r]))
        if heights[l] < heights[r]:
            l += 1                 # move the shorter side
        else:
            r -= 1
    return best

Layout 2: same-direction (fast/slow) pointers

Both pointers start at the left; the fast one reads ahead while the slow one writes or marks. The relative distance is the state.

Remove duplicates from a sorted array in place (Chapter 2): write lags read.

def remove_duplicates(nums):
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write

Partitioning (Dutch national flag, quicksort) also uses same-direction pointers to move elements into regions.

Layout 3: the sliding window

A window [l, r) moves right, growing on the right and shrinking on the left. It answers “longest/shortest/max subarray satisfying a property” in \(O(n)\) because each element enters and leaves the window once.

Fixed window. For “maximum sum of any k consecutive elements”, add the new element, remove the element leaving the window.

def max_sum_k(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]   # slide by one
        best = max(best, window)
    return best

Variable window. For “longest substring without repeating characters”, expand r; when a duplicate appears, shrink l until the window is valid again.

def longest_unique(s):
    seen, l, best = set(), 0, 0
    for r, ch in enumerate(s):
        while ch in seen:             # invalid -> shrink from the left
            seen.remove(s[l])
            l += 1
        seen.add(ch)
        best = max(best, r - l + 1)   # window [l, r]
    return best

The invariant is that [l, r] is always a valid window. The while loop looks nested but each character is added once and removed at most once: amortized \(O(n)\) (the same argument as the monotonic stack, Chapter 4).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.62cm, minimum height=0.58cm, font=\small\bfseries}]
  \foreach \v [count=\i from 0] in {a,b,c,a,b,c,b,b} { \node[c, fill=blue!8] at (\i*0.68,0) {\v}; }
  \draw[very thick, green!55!black, rounded corners=2pt] (-0.36,-0.36) rectangle (3.04,0.36);
  \node[font=\scriptsize\ttfamily, text=green!45!black] at (-0.68,0) {l};
  \node[font=\scriptsize\ttfamily, text=orange!75!black] at (3.4,0) {r};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.4,-0.7) {slide r; when invalid, slide l until valid again};
\end{tikzpicture}

Minimum window substring is the harder variable-window problem: expand until the window covers all required characters, then shrink to find the smallest such window, tracking the best.

from collections import Counter
def min_window(s, t):
    need = Counter(t)
    have, l, best = Counter(), 0, (0, float("inf"))
    required = len(need)
    formed = 0
    for r, ch in enumerate(s):
        if ch in need:
            have[ch] += 1
            if have[ch] == need[ch]:
                formed += 1
        while formed == required:          # window is valid -> try to shrink
            if r - l < best[1] - best[0]:
                best = (l, r)
            if s[l] in need:
                have[s[l]] -= 1
                if have[s[l]] < need[s[l]]:
                    formed -= 1
            l += 1
    return s[best[0]:best[1] + 1] if best[1] < len(s) else ""

Choosing the layout

Problem shape Layout
Sorted array, find a pair converging
In-place compaction / partition same-direction
Longest/max window with property variable slide
Sum of every fixed-size window fixed slide
Palindrome / reverse converging

The recognition cue: “contiguous subarray/substring” plus “longest/shortest/max” almost always means a sliding window; “sorted” plus “pair/triplet” means converging pointers.

Pitfalls

QQuestionSelf-check

Why is a sliding window amortized \(O(n)\) despite the inner while? When do converging pointers require the array to be sorted?

ASolution

Each element is added when r reaches it and removed at most once when l passes it, so the total inner work across the scan is bounded by \(n\). Converging pointers rely on order: moving the smaller side can only improve the candidate, which is only valid when the array is sorted.

Next: Coding Interview Patterns (DSA #28) — the recurring shapes that combine everything in this course.