Browse curriculum

Introduction to Two Pointers

A space-efficient technique to traverse arrays and strings using two reference points significantly reducing time complexity.

Examples

Input:nums = [2,7,11,15], target = 9
Output:[0,1]
Explain:

Because nums[0] + nums[1] == 9, we return [0, 1].

Input:nums = [3,2,4], target = 6
Output:[1,2]

What is the Two Pointer Technique?

The Two Pointer technique is a fundamental strategy where you use two separate reference points (pointers) to traverse a data structure, usually an array or a string.

Instead of using a single loop to scan elements one by one (or nested loops to check every pair), we use two pointers to process information from different positions simultaneously. By moving these pointers based on specific conditions, we can solve problems much faster. This simple trick often turns a slow O(n^2) brute-force solution into an efficient O(n) linear solution.

The Motivation: Two Sum (Sorted)

Now, let's look at a classic problem to see why this technique is so useful.

"Given a sorted array of integers, find two numbers that sum up to a specific target."

Example:

  • Input: nums = [1, 3, 4, 6, 8, 10, 13]
  • Target: 13
  • Goal: Find two numbers that add to 13. (Answer: 3 + 10)

Attempt 1: Brute Force (Why it fails)

Your first instinct might be to check every single pair.

"Okay, let's try 1+3, 1+4, 1+6... then 3+4, 3+6..."

While this gives the correct answer, it is extremely inefficient.

  • Time Complexity: O(n^2). For an array of 10,000 items, that's 100 million checks!
  • The Issue: You are doing repetitive work and ignoring the most important clue: The array is sorted.

Visualizing the Brute Force Approach

Switch the figure further down to Check every pair to watch this: the nested loop computes sum after sum, most of which the sorted order could have ruled out.

When should I use Two Pointers?

Pattern Recognition Triggers:

In an interview, consider this pattern immediately if you see:

  1. Sorted Input: The problem mentions a "sorted array" or implies you can sort it.
  2. Pair/Triplet Search: You need to find sets of elements (pairs, triplets).
  3. Minimize/Maximize: You need to find a pair with min/max distance or sum.
  4. Opposite Ends: The logic suggests checking extremes (smallest vs largest).

The Intuition: Process of Elimination

Let's work smarter, not harder.
Instead of blindly checking pairs, let's use the sorted order to eliminate wrong answers.

Key Insight:
If the sum of our current pair is Too Big, keeping the larger number is useless. It will always trigger a "Too Big" result with any other number. So, we can permanently discard (eliminate) the larger number.

Interactive Walkthrough

TARGET 13 · SORTED

CHECK PAIR

i

1

0

j

3

1

4

2

6

3

8

4

10

5

13

6

Checks

1

Sum

4

Target

13

 

nums[0] + nums[1] = 1 + 3 = 4: not 13

Next

nums[0] + nums[2] = 1 + 4 = 5: not 13

Sorted array

Target

Legend & Complexity

The pair being added: i and j, or L and R

The pair that sums to the target

Two pointers: values already ruled out

L

Pointers are named above their cells

Check every pair

O(n²)

Two pointers

O(n)

Space

O(1)

Compare the two methods on the same array: Check every pair tries sums one by one, while Two pointers moves one pointer per sum and rules out every pair it passes. Checks counts the sums each computes.

Dry Run Table

Step Left Pointer (val) Right Pointer (val) Sum Action
1 Index 0 (1) Index 6 (13) 14 > 13. Too big. Move Right --
2 Index 0 (1) Index 5 (10) 11 < 13. Too small. Move Left ++
3 Index 1 (3) Index 5 (10) 13 == 13. Found it! Return True

The Solution Template

The two-pointer loop: compare the pair’s sum with the target and move the pointer that can bring it closer.

Introduction to Two Pointers Code
1function twoSum(nums, target) {
2 let left = 0;
3 let right = nums.length - 1;
4
5 while (left < right) {
6 let sum = nums[left] + nums[right];
7 if (sum === target) return true;
8 else if (sum < target) left++;
9 else right--;
10 }
11 return false;
12}

Edge Cases & Common Mistakes

Edge Case Checklist:

  • Empty Array: Return false/empty immediately.
  • One Element: Loop condition left < right handles this naturally (won't run).
  • No Solution: Ensure you handle the return value after the loop finishes.

Common Mistakes:

  • Not Sorting: The opposite-ends pair search only works on a sorted array. If the input is unsorted, sort it first (O(n log n)), or use a hash map when the original indices matter.
  • Wrong Loop Condition: Use left < right for pairs. Use left <= right only if a single element can be the answer.

Summary

Recap:

  • The Trick: Use sorted order to eliminate pairs.
  • Movement: Sum too small → Increase left. Sum too big → Decrease right.
  • Efficiency: We turned a slow O(n^2) search into a blazing fast O(n) scan.

The approach, step by step

  1. Place the pointers

    Put left at the first index and right at the last index of the sorted array.

  2. Compare the sum

    Add the two values and compare the sum with the target.

  3. Move one pointer

    Return on a match; move left in when the sum is too small, right in when it is too big; stop when they meet.

Frequently asked questions

What is the two pointers technique?

Two indices move through the same array, often from opposite ends. Each comparison moves one of them, so a single pass rules out whole groups of pairs instead of testing every pair with nested loops.


Why does the array need to be sorted for the opposite-ends pair search?

Sorting is what makes a move safe. If the sum is too small, the left value is too small for every value still on the right, so left can move in; if it is too big, right can move in. Without sorted order neither conclusion holds.


What is the time complexity of two pointers compared with brute force?

The pointer scan is O(n) time and O(1) extra space, because each step moves a pointer and they can move at most n times in total. Checking every pair is O(n²).

Want to see the mechanism first? Step through it in the visualizer:

Two Pointers

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description