Data Structures

Introduction to Two Pointers

2 min read
Data StructuresAlgorithmsTwo PointersArraysLinked ListsJavaScript

Nested loops were my go-to solution for array problems until I discovered the two pointers technique. It's amazing how often you can turn O(n²) into O(n) just by using two pointers strategically. This technique has become one of my favorite optimization tools.

What Are Two Pointers?

The idea is simple: use two pointers (or indices) to traverse data. They can move together, in opposite directions, or at different speeds. This often turns O(n²) solutions into O(n) ones.

My First Two Pointers Problem

I was trying to find two numbers in a sorted array that sum to a target. My first attempt used nested loops:

function twoSumNaive(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) {
        return [i, j];
      }
    }
  }
  return [];
}

This was O(n²). Then I learned about two pointers!

The Two Pointers Solution

The key insight: if the array is sorted, I can start from both ends and move inward:

function twoSum(nums, target) {
  let left = 0;
  let right = nums.length - 1;

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

    if (sum === target) {
      return [left, right];
    } else if (sum < target) {
      left++; // Need a larger sum, move left pointer right
    } else {
      right--; // Sum too large, move right pointer left
    }
  }

  return []; // No solution found
}

Why This Works

Since the array is sorted:

  • If sum is too small, moving left pointer right increases the sum
  • If sum is too large, moving right pointer left decreases the sum
  • We're guaranteed to find the answer (if it exists) in one pass

When I Use Two Pointers

I've found this technique works great for:

  • Sorted arrays: Finding pairs, triplets, or ranges
  • Palindrome checking: Comparing from both ends
  • Partitioning: Separating elements based on conditions
  • Cycle detection: Using fast and slow pointers

What I Learned

Two pointers taught me:

  • Sometimes one pass is enough if I'm smart about pointer movement
  • Sorted data opens up optimization opportunities
  • This technique appears in many interview problems
  • It's a pattern worth recognizing early

Key Takeaways

  • Two pointers can reduce O(n²) to O(n) for many problems
  • Works especially well with sorted data
  • The pointers can move together, apart, or at different speeds
  • Recognizing this pattern saves time and makes code cleaner

I've found that two pointers is one of those techniques that, once you see it, you start noticing it everywhere. It's become one of my first thoughts when I see array or linked list problems. I hope this helps you recognize when two pointers can simplify your solutions!

Share:
Loading reactions...

Loading comments...