Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · DSA

Array and String Patterns: Two Pointers and Sliding Window

Two of the most reusable techniques for array and string problems. Learn when to use opposing pointers and how a sliding window turns nested loops into a single pass.

Many array and string problems that look like they need nested loops can be solved in a single pass. Two patterns do most of the work: two pointers, which walk indices toward each other or at different speeds, and the sliding window, which maintains a contiguous range and adjusts its edges. Both reduce an O(n squared) brute force to O(n).

Two Pointers: Opposite Ends

When the input is sorted, two indices starting at opposite ends can converge based on a comparison. The classic case is finding a pair that sums to a target.

def two_sum_sorted(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return (lo, hi)
        if s < target:
            lo += 1   # need a larger sum
        else:
            hi -= 1   # need a smaller sum
    return None

Because the array is sorted, moving the left pointer can only increase the sum and moving the right can only decrease it, so no valid pair is skipped. Each index moves at most n times, giving O(n) time and O(1) space.

The same converging idea reverses a string in place, checks a palindrome, or merges two sorted arrays from the back.

Two Pointers: Fast and Slow

A second variant runs two pointers over the same sequence at different speeds. It removes duplicates from a sorted array in place:

def dedupe_sorted(nums):
    if not nums:
        return 0
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write   # new length

The read pointer scans every element while the write pointer marks where the next unique value belongs. Fast and slow pointers also detect cycles in linked lists, where one moves two steps per one step of the other.

The Sliding Window

A sliding window maintains a contiguous subarray or substring and expands or shrinks it to satisfy a constraint. It fits problems about the longest, shortest, or best contiguous range.

Consider the longest substring without repeating characters.

def longest_unique(s):
    seen = {}
    start = 0
    best = 0
    for end, ch in enumerate(s):
        if ch in seen and seen[ch] >= start:
            start = seen[ch] + 1   # jump past the repeat
        seen[ch] = end
        best = max(best, end - start + 1)
    return best

The window is the range from start to end. When a repeat appears inside the window, the left edge jumps past the previous occurrence. Each character is visited a constant number of times, so the algorithm is O(n) time and O(k) space where k is the alphabet size.

Fixed-Size Windows

When the window length is fixed, maintain a running aggregate and slide by adding the entering element and removing the leaving one. This finds the maximum sum of any k consecutive numbers.

def max_window_sum(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

Recomputing each window from scratch would be O(n times k). Reusing the previous sum makes it O(n).

Choosing the Pattern

A few signals help pick the right tool:

  • The array is sorted and a pair or triple is wanted: opposing two pointers.
  • Modify an array in place with a stable order: fast and slow pointers.
  • Longest or shortest contiguous range under a constraint: variable sliding window.
  • A statistic over every fixed-length block: fixed sliding window.

A Worked Walkthrough

Find the smallest subarray whose sum is at least a target. Expand the window by moving the right edge and adding values. Once the sum reaches the target, shrink from the left while the condition still holds, recording the smallest length.

def min_subarray_len(target, nums):
    start = 0
    total = 0
    best = float('inf')
    for end in range(len(nums)):
        total += nums[end]
        while total >= target:
            best = min(best, end - start + 1)
            total -= nums[start]
            start += 1
    return 0 if best == float('inf') else best

The right edge advances n times and the left edge advances at most n times total, so even with the inner while loop the work is O(n). The key insight is that each pointer only moves forward, never backward, which is what keeps these patterns linear.

Common Mistakes

  • Forgetting to shrink the window, which leaves it monotonically growing and wrong.
  • Comparing against a stale index after the window start has moved.
  • Using a variable window when the problem actually fixes the length, or the reverse.

Mastering these two shapes covers a large fraction of array and string interview questions.