← Back

👈👉Two Pointers Pattern

Interactive Visualization

👶Explain Like I'm 5

Imagine you're trying to find two kids in a line whose ages add up to exactly 10...

You put one finger on the youngest kid (left) and another on the oldest kid (right). If their ages add up to more than 10, move your right finger to a younger kid (←). If it's less than 10, move your left finger to an older kid (→). Keep going until you find the pair!

Why is this smart? Instead of checking every possible pair (slow! 🐌), you smartly eliminate bad options and move closer to the answer (fast! 🚀).

Real-world use cases:

  • Find pair of items that match a budget
  • Remove duplicates from sorted list
  • Check if a string is a palindrome
  • Merge two sorted lists

Problem: Find Two Numbers That Add to Target

Array (sorted): [1,2,3,4,5,6,7,8,9] | Target: 10

1
👈LEFT
2
3
4
5
6
7
8
9
RIGHT👉
Current Attempt
1
+
9
=
0
Left Index
0
Right Index
8
Target
10
Attempts
0

🎯 Click "Play" or "Next Step" to start!

💻Code Template

Copy this pattern!
function twoSum(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left < right) {
    const sum = arr[left] + arr[right];

    if (sum === target) {
      return [left, right]; // Found it!
    } else if (sum < target) {
      left++;  // Need bigger sum, move left →
    } else {
      right--; // Need smaller sum, move right ←
    }
  }

  return []; // No pair found
}

// Time: O(n) - Only one pass through array!
// Space: O(1) - No extra storage!
// NOTE: Array must be SORTED for this to work!

🎯When to Use Two Pointers?

Array is SORTED (or you can sort it first)
Looking for: pairs, triplets that meet a condition
Need to: remove duplicates in-place, reverse, or check palindrome
Can eliminate: Bad options by moving pointers smartly
⚠️
Remember: Fast/Slow variant (same direction) for linked lists!