2. Linear Patterns, Stacks & Queues

Two Pointers & Sliding Window Patterns

Eliminate nested loops on sorted arrays and contiguous subarrays/substrings using converging Two Pointers and shrink-on-violation Sliding Windows in O(n) time.

7 min readUpdated 2026-11-30
In This Lesson
  • Use converging left/right pointers on sorted arrays in O(n) time and O(1) space
  • Maintain a variable-size sliding window that expands right and shrinks left cleanly
  • Recognize when a problem fits Sliding Window (contiguous subarray/substring) vs Hash Map

When an interview problem asks about pairs in a sorted array or the longest/shortest contiguous subarray or substring, reach immediately for Two Pointers or Sliding Window to drop O(n²) brute force down to O(n) time and often O(1) space.

Why It Matters: The Problem with Brute Force

Consider Longest Substring Without Repeating Characters on a string s of length n:

  • Brute force: Try every start index i and end index j, checking if s[i : j + 1] has all unique characters → O(n³) naive, or O(n²) with a set per start i.
  • Sliding Window: Keep a single active window [left..right] with a seen set. As right moves forward, shrink left just until the duplicate disappears → O(n) time!

Pattern 1: Converging Two Pointers (left = 0, right = len(arr) - 1)

When an array is sorted (or an area formula depends on width = right - left), place left at the start and right at the end, then move one pointer inward based on a comparison:

python
from typing import Optional

def two_sum_sorted(nums: list[int], target: int) -> Optional[tuple[int, int]]:
    left, right = 0, len(nums) - 1
    while left < right:
        s = nums[left] + nums[right]
        if s == target:
            return (left, right)
        if s < target:
            left += 1   # Need a larger sum
        else:
            right -= 1  # Need a smaller sum
    return None

Dry-Run Trace: max_water_container([1, 8, 6, 2, 5, 4, 8, 3, 7])

The area between bars left and right is (right - left) * min(heights[left], heights[right]). Because moving inward shrinks width, keeping the taller bar and moving the shorter bar inward is the only chance to find a larger area.

Stepleft (h[L])right (h[R])WidthAreabestPointer Move
10 (1)8 (7)88 × 1 = 88h[L] < h[R] → left = 1
21 (8)8 (7)77 × 7 = 4949h[R] <= h[L] → right = 7
31 (8)7 (3)66 × 3 = 1849right = 6
41 (8)6 (8)55 × 8 = 4049right = 5
5–8......<= 4<= 3249Loop ends when left == right

Pattern 2: Variable-Size Sliding Window

Variable Sliding Window: Expand Right, Shrink Left
0
a
L→
b
2
c
←R
a
4
b
5
c

Active window [L..R] = "bca" (length 3) · duplicate 'a' at idx 3 forces L from 0 → 1

Each pointer moves forward at most n times total, keeping worst-case runtime strictly O(n).

Mental Model: The Caterpillar Crawling Forward

Think of [left..right] as a caterpillar crawling across s:

  1. Expand right: Add s[right] to the window state.
  2. Shrink left while invalid: While the window violates the rule (e.g., ch in seen or window_sum >= target), remove s[left] and increment left += 1.
  3. Update best: Record right - left + 1 once the window is valid again.

Step-by-Step Trace: longest_unique_substring("pwwkew")

Interactive Walkthrough: Sliding Window on "pwwkew"Step 1 / 6
L,R
p
w
w
k
e
w
seen = {'p'}best = 1

Step 1: Expand R=0 ('p')

'p' is not in seen. Add 'p' → window='p', best=1.

rightchInvalid (ch in seen)?Shrink Actions (left += 1)Window [left..right]best
0'p'No—"p" (left=0)1
1'w'No—"pw" (left=0)2
2'w'Yes ('w' in seen)Remove 'p' (left=1), remove 'w' (left=2)"w" (left=2)2
3'k'No—"wk" (left=2)2
4'e'No—"wke" (left=2)3
5'w'Yes ('w' in seen)Remove 'w' (left=3)"kew" (left=3)3

Because both left and right only move forward from 0 to n - 1, total pointer steps are at most 2n → strictly O(n) time!

Edge Cases to Always Verify

  • Empty string / array ("" or []): for right in range(0) never runs, returning 0 cleanly.
  • Single element ("a"): Window [0..0] has length 1.
  • All identical items ("bbbbb"): Shrinks left to equal right every turn, returning 1.
  • while left < right: vs while left <= right:: Use left < right when you need two distinct indices (like Two Sum or Container With Most Water); use left <= right only when a single-element check is valid (like palindrome verification or binary search).
Forgetting to Remove s[left] Before Incrementing left

In the shrink loop, always remove s[left] from your window state (seen.remove(s[left]) or window_sum -= nums[left]) before writing left += 1. Incrementing first removes the wrong element and causes subtle off-by-one bugs!

Pro Optimization: Jump left Directly with Last-Seen Index

For longest_unique_substring, storing last_idx[ch] = right in a dict lets you jump left = max(left, last_idx[ch] + 1) in O(1) instead of popping characters one by one.

Pattern Recognition: Two Pointers vs Sliding Window vs Prefix Sum

Problem CluePatternComplexity
Sorted array: find pair/triplet summing to targetConverging Two PointersO(n) time, O(1) space
Remove duplicates / partition array in-placeRead/Write Two PointersO(n) time, O(1) space
Longest/shortest contiguous subarray with monotonic ruleSliding WindowO(n) time
Subarray sum equals k with negative numbersPrefix Sum + Hash MapO(n) time, O(n) space

Try It Yourself in the Playground

Test Longest Substring Without Repeating Characters, Container With Most Water, and Minimum Size Subarray Sum right in your browser:

Python 3Try It Live: Sliding Window & Two Pointers
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why is the time complexity of longest_unique_substring O(n) even though there is a while loop nested inside the for loop?

Quick Checkpoints

Check Your Understanding

In max_water_container, why do we advance the shorter pointer (heights[left] < heights[right] -> left += 1)?

Check Your Understanding

Which keyword clue in a problem statement strongly suggests a Sliding Window approach?

Check Your Understanding

In longest_unique_substring, what happens if you increment left += 1 BEFORE calling seen.remove(s[left])?