01 / 20

Two-Pointer &
Sliding Window

Master two foundational array and string patterns in C++ that reduce brute-force \( O(n^2) \) solutions to elegant \( O(n) \) algorithms.

C++ Algorithms

What Is the Two-Pointer Pattern?

The two-pointer technique uses two index variables that traverse a data structure, often moving toward each other or in the same direction, to solve problems in \( O(n) \) time instead of \( O(n^2) \).

1 3 5 7 9 11 14 left right converge toward each other

What Is the Sliding Window Pattern?

A sliding window maintains a contiguous sub-range of the array. Instead of re-computing from scratch, you slide the window forward: add the new element entering the right side and remove the element leaving the left side.

2 4 1 6 3 8 5 window (size 3) slide right by 1

Why Do These Patterns Matter?

\( O(n^2) \) Brute Force
Nested loops check every pair or subarray. For \( n = 10^6 \), that is \( 10^{12} \) operations: far too slow.
\( O(n) \) Optimized
Two-pointer and sliding window eliminate redundant work. You visit each element at most twice: once when entering, once when leaving.

Core Rule: Two-Pointer on Sorted Data

Given a sorted array and a target value, place one pointer at the start and one at the end. If the current sum is too small, advance the left pointer. If too large, retreat the right pointer.

\( \text{sum} = \text{arr}[L] + \text{arr}[R] \)
\( \text{sum} < \text{target} \)
\( L\text{++} \)
\( \text{sum} == \text{target} \)
Found!
\( \text{sum} > \text{target} \)
\( R\text{--} \)
Repeat while \( L < R \)
Time: \( O(n) \)   Space: \( O(1) \)

Core Rule: Sliding Window Template

The general sliding window maintains a range \[L, R\]. Expand \( R \) to include more elements, and shrink \( L \) when a constraint is violated.

1
Initialize: Set \( L = 0 \), \( R = 0 \), and a running state (sum, count, map).
2
Expand: Add \( \text{arr}[R] \) to the window state, then increment \( R \).
3
Shrink: While the window violates the constraint, remove \( \text{arr}[L] \) and increment \( L \).
4
Record: Update the answer (max length, min length, etc.).

Two-Pointer vs Sliding Window

Two-Pointer Sliding Window
Pointer Movement Opposite ends inward or same direction Both move left-to-right
Data Requirement Often sorted Usually unsorted is fine
Typical Problems Pair sum, palindromes, merging Max/min subarray, substring constraints
Window State No aggregate state needed Running sum, frequency map, etc.
Complexity \( O(n) \) time, \( O(1) \) space \( O(n) \) time, \( O(1) \) to \( O(k) \) space

How to Recognize & Apply

1
Spot the signal: problem asks about pairs, subarrays, or substrings of a contiguous range.
2
Check monotonicity: does expanding the window only make the property "more true" or "more false"? If yes, sliding window works.
3
Sorted input? Opposite-direction two-pointer is likely. Unsorted? Same-direction (sliding window) is likely.
4
Define the state: what do you track as the window changes? A sum, a frequency count, a set?
5
Write the loop: expand with \( R \), shrink with \( L \), update answer each iteration.

Example 1: Two Sum (Sorted Array)

Problem: given a sorted array, find two numbers that add up to target \( = 12 \).

1 3 5 7 9 11 14 L R 1 + 14 = 15 > 12 → move R left
vector<int> twoSum(vector<int>& arr, int target) { int L = 0, R = arr.size() - 1; while (L < R) { int sum = arr[L] + arr[R]; if (sum == target) return {L, R}; else if (sum < target) L++; else R--; } return {-1, -1}; }

Two Sum: Step-by-Step

1
\(L=0\), \(R=6\): \( 1 + 14 = 15 > 12 \) → \(R\text{--}\)
2
\(L=0\), \(R=5\): \( 1 + 11 = 12 = 12 \) → Found! Return {0, 5}

Example 2: Max Sum of Size \( k \) Window

Problem: find the maximum sum of any contiguous subarray of length \( k = 3 \).

2 5 1 8 3 7 sum = 14
\( \text{Next: subtract arr}[1]=5, \text{ add arr}[4]=3 \rightarrow \text{sum} = 12 \)
int maxSumK(vector<int>& arr, int k) { int sum = 0; for (int i = 0; i < k; i++) sum += arr[i]; int best = sum; for (int i = k; i < arr.size(); i++) { sum += arr[i] - arr[i - k]; // slide best = max(best, sum); } return best; }

Example 3: Longest Substring Without Repeats

Problem: find the length of the longest substring with all unique characters in "abcabcbb".

a b c a b c b b
\(L\)
\(R\) (duplicate!)
"abc" is unique (len 3). 'a' repeats → shrink L until no duplicate.

Variable Window: The Code

int lengthOfLongestSubstring(string& s) { unordered_set<char> seen; int L = 0, best = 0; for (int R = 0; R < s.size(); R++) { while (seen.count(s[R])) { seen.erase(s[L]); L++; } seen.insert(s[R]); best = max(best, R - L + 1); } return best; }

Common Mistakes to Avoid

✕ Forgetting to Sort
Opposite-direction two-pointer only works on sorted arrays. Applying it to unsorted data gives wrong results silently.
✕ Off-by-One in Window Size
Window length is \( R - L + 1 \), not \( R - L \). Missing the +1 underestimates every window by one element.
✕ Not Shrinking Properly
When the constraint breaks, you must shrink while (not if) the condition holds. A single if may leave the window invalid.

Pattern Summary

Aspect Opposite Two-Pointer Fixed Window Variable Window
Pointers L at start, R at end L and R move together R always advances, L catches up
Pre-sort? Yes No No
State None Running aggregate Map/set + aggregate
Use Case Pair sum, triplet Max sum of size \( k \) Longest valid substring
Time \( O(n) \) \( O(n) \) \( O(n) \)

Question 1 of 5

What is the time complexity of finding a pair with a given sum in a sorted array using the two-pointer technique?

Question 2 of 5

In a fixed-size sliding window of size \( k \), how do you update the window sum when sliding one position to the right?

Question 3 of 5

When using opposite-direction two-pointer for pair sum, why must the array be sorted?

Question 4 of 5

What is the bug in this code?

Question 5 of 5

You need to find the minimum length subarray whose sum is at least \( S \) in an array of positive integers. Which pattern is most appropriate?