Workspace / Learning hub
Sliding WindowDSA ROADMAP · 02 / 30
LESSON 2 · TWO POINTERS

Let two positions do the searching.

Use two pointers to narrow a search space without checking every possible pair.

THE IDEAStart two pointers in useful places, then move one at a time.

The pointers may begin at opposite ends or move together through a sequence. Each move should discard possibilities while preserving the answer you are looking for.

When does this pattern help?

Two pointers are useful for pairs in a sorted array, comparing characters from both ends, removing duplicates in place, or finding a range that meets a condition. The key is knowing which pointer movement makes sense from the current values.

OPPOSITE ENDS

Start at the beginning and end of a sorted array. Move inward based on whether the current result is too small or too large.

SAME DIRECTION

Move a slow pointer to track a position to keep, while a fast pointer scans ahead for useful values.

A CLOSER EXPLANATION

A pointer is an index or reference that moves through data. The main benefit is that a comparison tells you which direction can safely eliminate candidates. Opposite-end pointers often work on sorted data; same-direction pointers are useful when scanning and compacting in place.

WATCH THE POINTERS MOVE

Find two values that sum to 12

1 / 4
CURRENT SUM10
TARGET12

Start at both ends. 1 + 9 = 10, which is below 12. Move the left pointer inward to make the sum larger.

How to choose which pointer moves

  1. Use the ordering: this example works because the values are sorted.
  2. Sum too small? Move the left pointer right to increase the sum.
  3. Sum too large? Move the right pointer left to decrease the sum.

For an unsorted array, this sum rule does not work as-is. Sorting may help, but consider whether sorting changes the question or loses the original indices.

NOW YOU TRY

Find a pair in a sorted array

Given the sorted array [1, 3, 4, 6, 8, 10] and target 14, enter any pair of values that adds up to the target. Enter 0 if no pair exists.

YOUR GOALnumbers = [1, 3, 4, 6, 8, 10]
target = 14
Return the pair of values.
Show a hint

Begin with 1 and 10. Their sum is 11, so move the left pointer toward larger values.

CONNECT IT TO REAL LIFE

Two Pointers at work

A shop has sorted item prices [2, 5, 7, 11, 14]. Can you find two items that cost exactly 16 together?

Show one possible approach

Yes: 2 + 14 = 16. Start with the cheapest and most expensive prices; because the total matches, you can stop.