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.
- 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
iand end indexj, checking ifs[i : j + 1]has all unique characters →O(n³)naive, orO(n²)with a set per starti. - Sliding Window: Keep a single active window
[left..right]with aseenset. Asrightmoves forward, shrinkleftjust 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:
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 NoneDry-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.
| Step | left (h[L]) | right (h[R]) | Width | Area | best | Pointer Move |
|---|---|---|---|---|---|---|
| 1 | 0 (1) | 8 (7) | 8 | 8 × 1 = 8 | 8 | h[L] < h[R] → left = 1 |
| 2 | 1 (8) | 8 (7) | 7 | 7 × 7 = 49 | 49 | h[R] <= h[L] → right = 7 |
| 3 | 1 (8) | 7 (3) | 6 | 6 × 3 = 18 | 49 | right = 6 |
| 4 | 1 (8) | 6 (8) | 5 | 5 × 8 = 40 | 49 | right = 5 |
| 5–8 | ... | ... | <= 4 | <= 32 | 49 | Loop ends when left == right |
Pattern 2: Variable-Size Sliding Window
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:
- Expand
right: Adds[right]to the window state. - Shrink
leftwhile invalid: While the window violates the rule (e.g.,ch in seenorwindow_sum >= target), removes[left]and incrementleft += 1. - Update best: Record
right - left + 1once the window is valid again.
Step-by-Step Trace: longest_unique_substring("pwwkew")
Step 1: Expand R=0 ('p')
'p' is not in seen. Add 'p' → window='p', best=1.
right | ch | Invalid (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, returning0cleanly. - Single element (
"a"): Window[0..0]has length1. - All identical items (
"bbbbb"): Shrinksleftto equalrightevery turn, returning1. while left < right:vswhile left <= right:: Useleft < rightwhen you need two distinct indices (like Two Sum or Container With Most Water); useleft <= rightonly when a single-element check is valid (like palindrome verification or binary search).
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!
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 Clue | Pattern | Complexity |
|---|---|---|
Sorted array: find pair/triplet summing to target | Converging Two Pointers | O(n) time, O(1) space |
| Remove duplicates / partition array in-place | Read/Write Two Pointers | O(n) time, O(1) space |
| Longest/shortest contiguous subarray with monotonic rule | Sliding Window | O(n) time |
Subarray sum equals k with negative numbers | Prefix Sum + Hash Map | O(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:
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
In max_water_container, why do we advance the shorter pointer (heights[left] < heights[right] -> left += 1)?
Which keyword clue in a problem statement strongly suggests a Sliding Window approach?
In longest_unique_substring, what happens if you increment left += 1 BEFORE calling seen.remove(s[left])?