Two Pointers Technique

An optimization technique that uses two pointers to process linear data structures in O(n) time.

Two Pointers Simulation

Visualize pointer collaboration logic step-by-step.

Pattern: Two Sum (Sorted)

"Start at both ends and meet in the middle."

// Opposite Direction
while (left < right) {
  const sum = arr[left] + arr[right];
  if (sum === target) return [left, right];
  if (sum < target) left++;
  else right--;
}

Time Complexity: O(n)

Significantly faster than nested loops (Brute Force O(n²)). We only pass through the array once.

Space Complexity: O(1)

No additional storage used. Modifies in-place.

1[0]
Left
2[1]
4[2]
6[3]
8[4]
10[5]
Right

Initialize pointers at both ends. Sum: 1 + 10 = 11

1 / 6

Detailed explanation about Two Pointers Technique.