Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

Introduction to Two Pointers Pattern

Core idea

How it works

Recognize it when

The template

Variants in this chapter

Watch out for

How this compares with nearby patterns

Key Takeaways

You are given a sorted array of numbers and a target sum. Find two numbers in the array that add up to that target.

[1, 3, 4, 6, 8, 11]     target = 10

The first approach most people try is to check every pair. Take the first number and compare it against every number after it. Then take the second number and do the same. With N numbers that is about N²/2 comparisons. For an array of 10,000 numbers, that is 50 million comparisons.

Now look at the array again. It is sorted, and the approach above never uses that fact.

Start with the smallest number and the largest number, 1 and 11. They add to 12, which is above the target of 10. Here is the useful part. 1 is the smallest partner that 11 will ever get. If 11 and 1 are already above the target, then 11 with any other number is above it too. So 11 can never be part of the answer, and every pair containing it can be dropped at once.

That is one comparison ruling out five pairs. Repeat the same reasoning and the answer is found in five comparisons instead of fifteen.

Core idea

The Two Pointers pattern keeps two indices into the same array and moves them under a rule. Every move discards a part of the search space that cannot contain the answer. A nested loop that checked every pair becomes a single pass.

The rule is what makes it correct. It normally comes from the array being sorted, because sorted order tells you which direction makes the result larger and which makes it smaller.

How it works

For the pair sum question, the steps are:

  1. Put left at index 0 and right at the last index.
  2. Add the two values they point at.
  3. If the sum equals the target, you are done.
  4. If the sum is below the target, move left one step right. Only a larger value can help.
  5. If the sum is above the target, move right one step left. Only a smaller value can help.
  6. Stop when the two pointers meet. If they meet without a match, no pair exists.
The two pointers converge on the pair that sums to 10, ruling out values at every step.
The two pointers converge on the pair that sums to 10, ruling out values at every step.

Each step removes at least one number from consideration, and no number is visited twice. That gives O(N) time, against O(N²) for the nested loops. The pointers are two integers, so the extra space is O(1).

Recognize it when

Use Two Pointers when the question shows these signs.

  • The input is sorted, or you are allowed to sort it first.
  • You are asked for a pair, a triplet, or a subarray that meets a condition. Common conditions are a target sum, a comparison, or a duplicate rule.
  • The question says "in place" or "using constant extra space".
  • Your first idea is two nested loops over the same array. This is the most reliable signal of the five. When you notice it, stop and ask whether moving one pointer could replace the inner loop.
  • You are comparing two sequences against each other, one pointer in each.

It is not this pattern when:

  • The array is unsorted and the question needs the original indices. Sorting destroys them.
  • You need a contiguous window whose size or contents change as you scan. That is Sliding Window.
  • The data is a linked list and the question asks about a cycle or a midpoint. That is Fast and Slow Pointers.

The template

Almost every problem in this chapter is a variation on this skeleton.

function findPair(array, target):
    left  = 0
    right = length(array) - 1

    while left < right:
        sum = array[left] + array[right]

        if sum == target:
            return [left, right]      # the condition is met
        if sum < target:
            left = left + 1           # need a larger value
        else:
            right = right - 1         # need a smaller value

    return []                         # the pointers met, nothing found

The skeleton has three decisions. while left < right is the stopping rule. The comparison in the middle is the test. The two moves decide what gets discarded.

For a different problem you change the comparison and change what gets returned. The skeleton stays the same.

Variants in this chapter

The same two pointers move in several different ways. These are the shapes used in this chapter.

VariantHow the pointers moveProblems in this chapter
Convergingone at each end, moving inwardPair with Target Sum, Squaring a Sorted Array, Minimum Window Sort
Same directiona slow writer and a fast reader, editing in placeFind Non-Duplicate Number Instances
Fixed value plus a pairan outer loop fixes one number, two pointers handle the restTriplet Sum to Zero, Triplet Sum Close to Target, Triplets with Smaller Sum, Quadruple Sum
Partitioningthree pointers split the array into regionsDutch National Flag
One pointer per inputtwo sequences, one pointer walking eachComparing Strings containing Backspaces

Learn the converging variant first. The other four are easier to follow once it is familiar.

Watch out for

  • Forgetting to skip duplicates. In the triplet problems the same answer will be produced several times unless you advance past repeated values after a match.
  • Using the wrong stopping condition. left < right stops before a number is paired with itself. left <= right allows it. Which one you need depends on the question, so decide it deliberately.
  • Sorting when you must report original indices. Sort a copy that keeps each value paired with its original index, or use a hash map instead.
  • Moving both pointers after a comparison that failed. Only the side that can improve the result should move, otherwise you can skip past the answer.
  • Assuming sorted input. If the question does not promise it, sorting costs O(N log N) and that becomes the real complexity of your solution.

How this compares with nearby patterns

If the question asks forUse
a pair or triplet in a sorted arrayTwo Pointers
a contiguous subarray or substring that grows and shrinksSliding Window
a cycle or a midpoint in a linked listFast and Slow Pointers
one specific value in a sorted arrayModified Binary Search

Sliding Window is the pattern most often confused with this one, and it is the same idea under a different rule. There, both pointers move in one direction and the region between them is the answer. Here they move toward each other and the region between them is what is left to search.

Key Takeaways

  • Two Pointers replaces a nested loop with a single pass, taking O(N²) down to O(N).
  • It works because sorted order tells you which pointer to move.
  • Every move must discard values that cannot be part of any answer. If a move cannot justify that, the pattern does not apply.
  • The skeleton is fixed. The comparison and the return value are what change between problems.
  • Extra space stays O(1), which is often the reason this pattern is the expected answer.

Let's apply it to the first problem, Pair with Target Sum.

Hajin Kim

Hajin Kim

· 2 years ago

It would be awesome if I could just write up notes on the side of each material so I can refer back to it

S

surbhi

· 4 years ago

Hello, Are there any patterns for solving String related questions?

Show 2 replies
M

Mohammad Awad

· 4 years ago

hi

Show 1 reply
Puneeth

Puneeth

· 20 days ago

Two pointers technique is useful whenever we have a set of elements let's say a pair, a triplet or even a subarray given we have a sorted array and we have to fulfil certain constraints.

On This Page

Core idea

How it works

Recognize it when

The template

Variants in this chapter

Watch out for

How this compares with nearby patterns

Key Takeaways