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 and a target sum. Find two numbers that add up to the target.

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

A simple solution checks every possible pair. For each number, compare it with every number after it.

This solution uses two nested loops. Its time complexity is O(N²), where N is the number of values.

However, this solution ignores one important fact: the array is sorted.

Start with the smallest value, 1, and the largest value, 11. Their sum is 12, which is greater than 10.

Because 1 is the smallest value, every other pair that contains 11 will have a sum of at least 12. Therefore, 11 cannot be part of the answer. We can stop considering it.

Next, compare 1 and 8. Their sum is 9, which is less than 10. We now need a larger value. Because 1 is the smallest remaining value, it cannot be part of a valid pair.

Continue this process:

1 + 11 = 12   move the right pointer left
1 + 8  = 9    move the left pointer right
3 + 8  = 11   move the right pointer left
3 + 6  = 9    move the left pointer right
4 + 6  = 10   found the pair

We found the answer without checking every pair.

Core idea

A pointer is an index that shows a position in an array or string.

The Two Pointers pattern uses two indices at the same time. Each pointer moves according to a clear rule.

Every move removes values that cannot be part of the answer. This often replaces two nested loops with one pass through the data.

Sorted order is especially useful. It tells us which pointer to move when a value is too small or too large.

How it works

For the target-sum problem, follow these steps:

  1. Put the left pointer at the first index.
  2. Put the right pointer at the last index.
  3. Add array[left] and array[right].
  4. If the sum equals the target, return the two indices.
  5. If the sum is less than the target, move left one step right. This gives us a larger value.
  6. If the sum is greater than the target, move right one step left. This gives us a smaller value.
  7. Stop when left and right meet.

If the pointers meet before finding the target, no valid 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.

Let N be the number of values in the array.

At each step, at least one pointer moves. A pointer can move across the array only once. Therefore, the time complexity is O(N).

The algorithm stores only two indices and the current sum. Its extra space complexity is O(1).

The improvement is important:

  • Checking every pair takes O(N²) time.
  • Two Pointers takes O(N) time for this sorted pair-sum problem.

Recognize it when

Two Pointers may be useful when you see these signs:

  • The input is sorted, or you are allowed to sort it.
  • The problem asks for a pair or triplet that meets a condition.
  • The problem asks you to change an array in place.
  • The problem asks you to use constant extra space.
  • Your first solution uses two nested loops over the same array.
  • You are comparing two arrays or strings, with one position in each input.

The most useful signal is the nested loop. Ask this question: "Can one pointer replace the inner loop?"

Do not use this basic pattern when:

  • The array is unsorted and you must return the original indices. A hash map may be better.
  • You need a contiguous part of an array or string that grows and shrinks. Use Sliding Window.
  • You need to find a cycle or midpoint in a linked list. Use Fast and Slow Pointers.
  • You need to find one specific value in a sorted array. Use Modified Binary Search.

The template

This is the basic template for two pointers that move toward each other:

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

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

        if sum == target:
            return [left, right]

        if sum < target:
            left = left + 1
        else:
            right = right - 1

    return []

Three parts may change in another problem:

  1. The condition that you test.
  2. The rule that moves each pointer.
  3. The value that you return.

The loop structure often stays the same.

The condition left < right also matters. It stops one array value from being paired with itself.

Variants in this chapter

Two pointers do not always start at opposite ends. They can move in several ways.

VariantHow the pointers moveProblems in this chapter
Convergingstart at opposite ends and move inwardPair with Target Sum, Squaring a Sorted Array, Minimum Window Sort
Same directiona fast pointer reads and a slow pointer writesFind Non-Duplicate Number Instances
Fixed value plus a pairone loop fixes a value while two pointers find the remaining valuesTriplet Sum to Zero, Triplet Sum Close to Target, Triplets with Smaller Sum, Quadruple Sum
Partitioningpointers divide the array into different regionsDutch National Flag
One pointer per inputone pointer moves through each inputComparing Strings containing Backspaces

Start with the converging variant. It makes the main idea easiest to see.

Watch out for

  • Moving the wrong pointer. Move the pointer that can bring the result closer to the target.
  • Moving both pointers after a failed comparison. You may skip the correct answer.
  • Using the wrong stopping condition. Use left < right when one value cannot be used twice.
  • Forgetting duplicate values. Skip repeated values when a problem requires unique pairs or triplets.
  • Sorting without checking the output requirement. Sorting changes the original indices.
  • Ignoring the cost of sorting. Sorting an unsorted array takes O(N log N) time.

How this compares with nearby patterns

If the problem needs...Use...
a pair or triplet in a sorted arrayTwo Pointers
a contiguous range that grows or shrinksSliding Window
a cycle or midpoint in a linked listFast and Slow Pointers
one specific value in a sorted arrayModified Binary Search

Two Pointers and Sliding Window both use two indices. The difference is what the indices represent.

With Two Pointers, the indices usually show values that we are comparing. With Sliding Window, the indices show the boundaries of one contiguous range.

Key takeaways

  • A pointer is an index that shows a position in an array or string.
  • Two Pointers processes two positions at the same time.
  • Sorted order often tells you which pointer to move.
  • Each move must safely remove values that cannot be part of the answer.
  • The pair-sum example improves from O(N²) time to O(N) time.
  • The basic pair-sum solution uses O(1) extra space.

Now apply this pattern to Pair with Target Sum.

Puneeth

Puneeth

· a month 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.

Show 1 reply
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

Reading Progress

0%


Vote for new content

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