01 / 20

Two Pointers &
Sliding Window

Master two of the most powerful array traversal patterns in Python: efficiently solving problems that would otherwise require nested loops.

Computer Science Python Algorithms

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.

Two Pointers
Two indices that move toward each other or in the same direction through the data.
Sliding Window
A fixed or variable-size window defined by two pointers that slides across the array.

Why \( O(n^2) \) Hurts

Input Size (n) Operations
\( O(n^2) \)
\( O(n) \)
0 1k 2k

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

1 3 5 7 9 11 15 left right left moves → ← right moves

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

2 4 1 6 3 8 5 window (size k = 3)
\( \text{sum} = 4 + 1 + 6 = 11 \)
slide →

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

1
Identify the goal: Are you looking for a pair (two pointers) or a contiguous subarray (sliding window)?
2
Check prerequisites: Does the problem require sorted data? Can you define a valid window condition?
3
Initialize pointers: Set left and right at the appropriate starting positions.
4
Define the move rule: What condition causes each pointer to advance? Write the while or for loop.
5
Update state & track answer: Maintain running sum, max, or set as pointers move.

Example 1: Pair with Target Sum

Problem: Given sorted array [1, 3, 5, 7, 9, 11], find a pair that sums to 12.

1 3 5 7 9 11 left=0 right=5
\( 1 + 11 = 12 \) ✓
Target found! Return [0, 5]

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

Opposite Pointers
Sorted array pair problems: two sum, container with most water, palindrome check
Same-Direction
Remove duplicates, merge sorted arrays, linked list cycle detection
Fixed Window
Max/min/average of any subarray of exactly size \( k \)
Variable Window
Smallest subarray with sum \( > S \), longest substring with at most \( k \) distinct chars

Common Mistakes

✕ Forgetting Sorted Prerequisite
Opposite-direction two pointers only work on sorted data. Applying them to unsorted arrays gives wrong results.
✕ Off-by-One Window Size
Using \( i - k \) instead of \( i - k + 1 \) for window length, or initializing the first window incorrectly.
✕ Not Shrinking the Window
In variable window problems, forgetting the inner 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?