Two Pointers &
Sliding Window
Master two of the most powerful array traversal patterns in Python: efficiently solving problems that would otherwise require nested loops.
What Are Pointer Patterns?
Many array and string problems ask you to find a pair, subarray, or substring that meets some condition. A brute-force approach checks every possible combination, but pointer-based patterns let you skip unnecessary work by moving indices intelligently.
Why \( O(n^2) \) Hurts
With \( n = 10{,}000 \), brute force does \( 10^8 \) operations while a pointer-based approach does \( \sim 10^4 \). That is the difference between seconds and microseconds.
The Two Pointer Pattern
Place one pointer at the start and one at the end of a sorted array. Compare the sum of both elements to the target: if too small, move left right; if too large, move right left.
The Sliding Window Pattern
A sliding window maintains a contiguous subarray between two pointers. Instead of recomputing the sum from scratch, you subtract the element leaving the window and add the element entering it.
Two Pointers Template
def two_sum_sorted(nums, target): left, right = 0, len(nums) - 1 while left < right: curr = nums[left] + nums[right] if curr == target: return [left, right] elif curr < target: left += 1 # need larger sum else: right -= 1 # need smaller sum return []
Sliding Window Template
def max_sum_subarray(nums, k): window_sum = sum(nums[:k]) best = window_sum for i in range(k, len(nums)): window_sum += nums[i] - nums[i - k] best = max(best, window_sum) return best
Two Pointers vs. Sliding Window
| Two Pointers | Sliding Window | |
|---|---|---|
| Pointer Direction | Opposite ends or same direction | Both move left to right |
| Data Requirement | Often sorted | Unsorted is fine |
| Typical Goal | Find a pair / partition | Optimal subarray / substring |
| Window Size | N/A (no window) | Fixed or variable |
| State Maintained | Usually just indices | Sum, count, or hash map |
| Complexity | \( O(n) \) | \( O(n) \) |
How to Apply These Patterns
left and right at the appropriate starting positions.while or for loop.Example 1: Pair with Target Sum
Problem: Given sorted array [1, 3, 5, 7, 9, 11], find a pair that sums to 12.
Example 2: Max Sum Subarray of Size \( k \)
Problem: Given [2, 1, 5, 1, 3, 2] and \( k = 3 \), find the maximum sum of any contiguous subarray of size 3.
# Array: [2, 1, 5, 1, 3, 2], k = 3 # Window 1: [2, 1, 5] sum = 8 # Window 2: [1, 5, 1] sum = 8 - 2 + 1 = 7 # Window 3: [5, 1, 3] sum = 7 - 1 + 3 = 9 ← best! # Window 4: [1, 3, 2] sum = 9 - 5 + 2 = 6 # Answer: 9
Example 3: Smallest Subarray with Sum \( \ge S \)
Problem: Given [2, 1, 5, 2, 3, 2] and \( S = 7 \), find the length of the smallest contiguous subarray whose sum is \( \ge 7 \).
def min_subarray_len(s, nums): left = 0 window_sum = 0 min_len = float('inf') for right in range(len(nums)): window_sum += nums[right] # expand while window_sum >= s: min_len = min(min_len, right - left + 1) window_sum -= nums[left] # shrink left += 1 return min_len if min_len != float('inf') else 0
Same-Direction Two Pointers
Not all two-pointer problems use opposite ends. The fast and slow pointer variant moves both pointers in the same direction at different speeds.
def remove_duplicates(nums): # Remove duplicates in-place from sorted array if not nums: return 0 slow = 0 for fast in range(1, len(nums)): if nums[fast] != nums[slow]: slow += 1 nums[slow] = nums[fast] return slow + 1
When to Use Which Pattern
Common Mistakes
while loop that moves left forward when the condition is met.Question 1 of 5
What is the time complexity of the two-pointer approach for finding a pair that sums to a target in a sorted array of \( n \) elements?
Question 2 of 5
In a fixed-size sliding window of size \( k \), how do you compute the sum of the next window from the current sum?
Question 3 of 5
Given sorted array [1, 2, 4, 6, 10] and target 8, which pair does the two-pointer approach find?
Question 4 of 5
In a variable-size sliding window, what triggers the inner while loop that shrinks the window from the left?
Question 5 of 5
Which problem is best solved with a sliding window rather than opposite-direction two pointers?