Resourcesโ€บDSAโ€บTwo Pointers Technique
๐ŸงฎDSAโ€” Two Pointers Techniqueโฑ 8 min

Two Pointers Technique

Master the two pointers pattern to solve array and string problems in O(n) time with O(1) space.

๐Ÿ“…January 20, 2025โœTechTwitter.ioarrayspatternsinterview

What Is the Two Pointers Technique?

The two pointers technique uses two index variables that traverse a data structure โ€” usually from opposite ends or at different speeds โ€” to solve problems without nested loops.

It reduces many O(nยฒ) brute-force solutions down to O(n) time with O(1) space.


When to Use It

  • Sorted array / string problems
  • Finding pairs that sum to a target
  • Removing duplicates in-place
  • Reversing or palindrome checks
  • Sliding window variants

Pattern 1 โ€” Opposite Ends

Start one pointer at the left, one at the right. Move them toward each other based on a condition.

def two_sum_sorted(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        s = arr[left] + arr[right]
        if s == target:
            return [left, right]
        elif s < target:
            left += 1
        else:
            right -= 1
    return []

Classic problems: Two Sum II, Valid Palindrome, Container With Most Water.


Pattern 2 โ€” Same Direction (Fast & Slow)

Both pointers start at the same end. The fast pointer advances every step; the slow one only moves when a condition is met.

def remove_duplicates(arr):
    if not arr:
        return 0
    slow = 0
    for fast in range(1, len(arr)):
        if arr[fast] != arr[slow]:
            slow += 1
            arr[slow] = arr[fast]
    return slow + 1

Classic problems: Remove Duplicates, Move Zeroes, Linked List Cycle Detection.


Pattern 3 โ€” Sliding Window

A window defined by two pointers expands and contracts to track a subarray satisfying a constraint.

def longest_substring_no_repeat(s):
    seen = {}
    left = 0
    best = 0
    for right, ch in enumerate(s):
        if ch in seen and seen[ch] >= left:
            left = seen[ch] + 1
        seen[ch] = right
        best = max(best, right - left + 1)
    return best

Classic problems: Longest Substring Without Repeating Characters, Minimum Window Substring.


Key Insight

Ask yourself: can I express this constraint as a comparison between two positions in the array? If yes, two pointers likely applies.