IN 30 SECONDS

The Two Pointers technique is a clever strategy where you use two separate variables (pointers) to keep track of two different indices in a data structure simultaneously. Instead of using nested loops to compare items, you move these pointers based on specific rules. This simple trick transforms painfully slow O(N^2) operations into blistering fast O(N) operations.

THE REAL-WORLD ANALOGY

Imagine trying to find a matching pair of socks on a very long, organized clothing rack. A bad approach (nested loops) is taking the first sock, then walking down the entire rack to find its match, then taking the second sock, and walking down the rack again. The Two Pointers approach is putting your left hand at the start of the rack, your right hand at the end, and moving them toward each other. You cover the whole rack in just one pass!

PICTURE THIS

Target Sum: 10\nArray: [2, 3, 5, 8, 9]\n        ^           ^\n       Left        Right\n       (2)         (9)\n       2+9 = 11 (Too big, move Right leftward)\n\nArray: [2, 3, 5, 8, 9]\n        ^        ^\n       Left     Right\n       (2)      (8)\n       2+8 = 10 (Match found!)

This diagram shows the "Opposite Direction" pattern. Because the array is sorted, if our sum is too big, moving the Right pointer down decreases the sum. It is completely deterministic.

HOW IT ACTUALLY WORKS

  1. Setup: Place two pointers. Usually, one is at the start (index 0) and one is at the end (index N-1).
  2. Evaluate: Check the condition between the two elements the pointers are looking at.
  3. Move: If you need a larger value, move the left pointer up. If you need a smaller value, move the right pointer down.
  4. Terminate: Stop when the pointers meet or cross each other.

SHOW ME THE CODE

def find_pair_sum(sorted_arr, target):\n    left = 0\n    right = len(sorted_arr) - 1\n    \n    while left < right:\n        current_sum = sorted_arr[left] + sorted_arr[right]\n        \n        if current_sum == target:\n            return [sorted_arr[left], sorted_arr[right]]\n        elif current_sum < target:\n            left += 1  # Need more, move left pointer up\n        else:\n            right -= 1 # Need less, move right pointer down\n            \n    return None # No pair found

DRY RUN

Input: arr=[1, 2, 4, 6], target=6

StepPointersSumAction
1L=0(1), R=3(6)77 > 6, so move Right down
2L=0(1), R=2(4)55 < 6, so move Left up
3L=1(2), R=2(4)6Match! Return [2, 4]

SPEED & MEMORY

We only traverse the array once. At each step, one of the pointers moves, meaning we do at most N steps. We don't create any new arrays, so memory is basically zero.

ScenarioTimeSpace
Nested Loops (Bad)O(N^2)O(1)
Two Pointers (Good)O(N)O(1)

WHERE YOU'LL SEE IT IN REAL LIFE

  • Video processing: Finding a scene boundary by moving pointers from both ends of a video buffer.
  • String parsing: Reversing text or checking if a word is a palindrome.

TRAPS TO AVOID

  • Trap 1: Using it on unsorted arrays for sum problems. Fix: The array MUST be sorted for the left/right sum logic to work!
  • Trap 2: Crossing pointers accidentally. Fix: Always use `while left < right` (not `<=`) if you need distinct elements.
  • Trap 3: Over-complicating pointer movement. Fix: Move only one pointer at a time per condition.

PRACTICE

  1. Easy: Use two pointers to reverse an array in-place. (Hint: Swap elements at L and R, then move them inward).
  2. Medium: Remove duplicates from a sorted array using two pointers moving in the same direction.

TL;DR

  • Two pointers replace nested loops, turning O(N^2) into O(N).
  • Common patterns include "Opposite Direction" (start and end) and "Same Direction" (fast and slow).
  • For sum-based problems, the data must be sorted first.

REFERENCES CONSULTED

Referenced for verification — all content above is original. Checked standard patterns at GeeksforGeeks Two Pointers.

COVERED LOG UPDATE

Added: Day 3: Two Pointers