Back to Data Structures and Algorithms

Two Pointers Complete Guide

Algorithm • medium

Two-pointer techniques use two moving indices to avoid expensive nested loops.

Common variants: opposite-direction pointers on sorted data, same-direction window pointers, or slow/fast pointers for cycle/middle logic.

The core skill is defining how each pointer moves when a condition is true/false.

Typical Complexity Baseline

MetricValue
Typical traversalO(n)

See It

Concept Diagram

A small animated SVG that illustrates the core idea the moving parts you need to keep in your head when you read the rest of the guide.

Two pointers converge from both ends

Pointers walk inward; each comparison eliminates at least one position from the search.

target sum = 22 · sorted input134681011141721lo=0hi=91 + 21 = 22
Step 1/2Sorted array. Target sum = 22. lo at 0, hi at 9.

Watch First

Video Explainer

A quick visual walkthrough before the detailed sections pick the format that helps you learn fastest.

Mechanics

Core Concepts

The building blocks and terminology you need before everything else clicks. Skim or deep-read.

Left pointer

What it is Tracks lower/start boundary.

Why it matters Left pointer is a required building block for understanding how Two Pointers stays correct and performant on large inputs.

Right pointer

What it is Tracks upper/end boundary.

Why it matters Right pointer is a required building block for understanding how Two Pointers stays correct and performant on large inputs.

Movement rule

What it is Condition deciding which pointer advances.

Why it matters Movement rule is a required building block for understanding how Two Pointers stays correct and performant on large inputs.

Invariant

What it is Property that remains true while pointers move.

Why it matters Invariant is a required building block for understanding how Two Pointers stays correct and performant on large inputs.

Termination rule

What it is Stop condition such as left >= right.

Why it matters Termination rule is a required building block for understanding how Two Pointers stays correct and performant on large inputs.

Opposite-direction

What it is Pointers start at both ends and move inward.

Why it matters Pointers start at both ends and move inward. In Two Pointers, this definition helps you reason about correctness and complexity when inputs scale.

Same-direction

What it is Both pointers advance through sequence with different roles.

Why it matters Both pointers advance through sequence with different roles. In Two Pointers, this definition helps you reason about correctness and complexity when inputs scale.

Fast/slow

What it is One pointer moves faster to detect structure properties.

Why it matters One pointer moves faster to detect structure properties. In Two Pointers, this definition helps you reason about correctness and complexity when inputs scale.

Window shrink

What it is Move left pointer to restore constraint validity.

Why it matters Move left pointer to restore constraint validity. In Two Pointers, this definition helps you reason about correctness and complexity when inputs scale.

Stable partition

What it is Rearrange while preserving order in selected partitions.

Why it matters Rearrange while preserving order in selected partitions. In Two Pointers, this definition helps you reason about correctness and complexity when inputs scale.

Walkthrough

Putting It All Together

Every frame of the concept diagram, laid out top-to-bottom so you can scroll through the algorithm at your own pace.

Step 1/2
target sum = 22 · sorted input134681011141721lo=0hi=91 + 21 = 22

Sorted array. Target sum = 22. lo at 0, hi at 9.

Step 2/2
target sum = 22 · sorted input134681011141721lo=0hi=91 + 21 = 22 === target ✓

1 + 21 = 22. Match! Found pair.

Tradeoffs

How It Compares

When this technique wins, when it loses, and what to reach for instead.

vs. Hash map lookup

Choose this when Choose two pointers when sorted order already exists.

Tradeoff Hash map can avoid sort precondition but uses extra memory.

vs. Sliding window

Choose this when Choose two pointers for pair relation constraints.

Tradeoff Sliding window is stronger for range constraints on contiguous data.

vs. Brute force nested loops

Choose this when Choose two pointers for linear progress through data.

Tradeoff Requires clear movement logic; brute force is simpler but slower.

In Production

Real-World Stories

Where this shows up at real companies and what the on-call engineer learned the hard way.

Pinterest

Recommendation dedup and content curation pipelines use two-pointer merges over sorted candidate sets.

Takeaway Linear pointer scans scale well in ranking pipelines.

Datadog

Time-series merge/join tasks use pointer-based passes on sorted timestamps.

Takeaway Two-pointer traversal avoids heavy random access during stream processing.

Snowflake

Sorted block merge operations during query processing use pointer-driven loops.

Takeaway Pointer discipline is central to efficient sorted-data operations.

Code

Implementation

A clean reference implementation in TypeScript, Python, and Go. Switch languages with the toggle.

Move shorter side inward because area is limited by min(heightLeft, heightRight).

Complexity: Time O(n), Space O(1)

Container with most water style scan

function maxArea(heights: number[]): number {
  let leftIndex = 0
  let rightIndex = heights.length - 1
  let bestArea = 0

  while (leftIndex < rightIndex) {
    const width = rightIndex - leftIndex
    const area = width * Math.min(heights[leftIndex], heights[rightIndex])
    bestArea = Math.max(bestArea, area)

    if (heights[leftIndex] < heights[rightIndex]) leftIndex += 1
    else rightIndex -= 1
  }

  return bestArea
}

Watch Out

Common Problems and Failure Modes

The bugs and edge cases that bite engineers most often. Skim before you ship.

  • Moving both pointers when only one should move.
  • Forgetting to sort input when algorithm assumes sorted order.
  • Incorrect duplicate handling causing repeated results.
  • Missing termination condition leading to infinite loops.
  • Mutating shared pointers across helper functions without clear ownership.

Pro Tips

Tips and Tricks

Small habits that pay off every time you reach for this pattern.

  • Two pointers are strongest when movement rules are deterministic.
  • If one pointer moves backward frequently, you may need a different pattern.
  • In sorted arrays, move pointer that causes current comparison failure.
  • Name pointers semantically (leftIndex, rightIndex) to reduce mistakes.

Pattern Recognition

When to Use

Concrete signals that tell you this is the right pattern both at work and on LeetCode.

Real-system usage signals

  • Converts many O(n^2) scans into O(n) or O(n log n) workflows.
  • Works naturally with sorted arrays and string windows.
  • Keeps memory overhead low with in-place traversal.

LeetCode-specific tips (pattern-identification signals)

  • Identification signal: two positions move under deterministic rules (often from both ends or slow/fast patterns).
  • Identification signal: sorted data with pair/triplet target checks can avoid nested loops by moving pointers based on sum comparison.
  • If you can decide pointer movement from current comparison only, two-pointers is usually a fit.
  • For Two Pointers questions, start by naming the core invariant before writing code.
  • Use the constraint section to set time/space target first, then pick the data structure/algorithm.
  • Solve one tiny example by hand and map each transition to your variables before implementing.
  • Run adversarial cases: empty input, duplicates, max-size input, and sorted/reverse patterns when relevant.
  • During interviews, explain why your approach is the right pattern for this prompt, not just why the code works.

Practice

LeetCode Progression

A curated easy-to-hard problem ladder. Each one reinforces a specific aspect of the pattern.

#ProblemDifficultyTypical Complexity
1Valid PalindromeEasyO(n)
2Merge Sorted ArrayEasyO(n+m)
3Remove Duplicates from Sorted ArrayEasyO(n)
4Two Sum IIMediumO(n)
5Container With Most WaterMediumO(n)
63SumMediumO(n^2)
7Sort ColorsMediumO(n)
8Trapping Rain WaterHardO(n)
9Minimum Window SubstringHardO(n)
10Substring with Concatenation of All WordsHardO(n*k)