DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

πŸ‘† Two Pointers Explained Like You're 5

Scanning from both ends

Day 107 of 149

πŸ‘‰ Full deep-dive with code examples


The Dance Partners Analogy

Imagine a line of people finding dance partners:

  • One person starts from the left
  • Another starts from the right
  • They move toward each other until matched

Two Pointers works like this!

Two markers that move through data, often toward each other.


The Problem It Solves

Some problems need comparing pairs:

  • "Find two numbers that add to 10"
  • "Is this word a palindrome?"
  • "Remove duplicates from a sorted list"

Checking every possible pair is slow (every item with every other item).


How It Works

Instead of checking all pairs:

  1. Start with two pointers (often at opposite ends)
  2. Move them based on conditions
  3. Stop when they meet or find the answer

This is much faster because you eliminate many options with each move!


Classic Examples

Finding a pair that sums to target (sorted array):

Array: [1, 3, 5, 7, 9]  Target: 12

Left→ 1        Right→ 9  Sum=10 (too small, move left)
Leftβ†’ 3        Rightβ†’ 9  Sum=12 βœ“ Found!
Enter fullscreen mode Exit fullscreen mode

Checking palindrome:

"racecar"
L→ r           R→ r  Match!
L→ a           R→ a  Match!
L→ c           R→ c  Match!
L→ e           R→ e  (they meet) It's a palindrome!
Enter fullscreen mode Exit fullscreen mode

When To Use It

Two pointers works great when:

  • Data is sorted
  • Comparing elements from different positions
  • Finding pairs or ranges

Think: "Can I use two markers moving toward each other?"


In One Sentence

Two Pointers uses two markers moving through data to efficiently find pairs or ranges without checking every combination.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)