Visual introduction Two Pointer Algorithm
Channel: Josh's DevBox
Watch on YouTube →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
| Metric | Value |
|---|---|
| Typical traversal | O(n) |
See It
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.
Pointers walk inward; each comparison eliminates at least one position from the search.
Watch First
A quick visual walkthrough before the detailed sections pick the format that helps you learn fastest.
Channel: Josh's DevBox
Watch on YouTube →Mechanics
The building blocks and terminology you need before everything else clicks. Skim or deep-read.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
Every frame of the concept diagram, laid out top-to-bottom so you can scroll through the algorithm at your own pace.
Sorted array. Target sum = 22. lo at 0, hi at 9.
1 + 21 = 22. Match! Found pair.
Tradeoffs
When this technique wins, when it loses, and what to reach for instead.
Choose this when Choose two pointers when sorted order already exists.
Tradeoff Hash map can avoid sort precondition but uses extra memory.
Choose this when Choose two pointers for pair relation constraints.
Tradeoff Sliding window is stronger for range constraints on contiguous data.
Choose this when Choose two pointers for linear progress through data.
Tradeoff Requires clear movement logic; brute force is simpler but slower.
In Production
Where this shows up at real companies and what the on-call engineer learned the hard way.
Recommendation dedup and content curation pipelines use two-pointer merges over sorted candidate sets.
Takeaway Linear pointer scans scale well in ranking pipelines.
Time-series merge/join tasks use pointer-based passes on sorted timestamps.
Takeaway Two-pointer traversal avoids heavy random access during stream processing.
Sorted block merge operations during query processing use pointer-driven loops.
Takeaway Pointer discipline is central to efficient sorted-data operations.
Code
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
The bugs and edge cases that bite engineers most often. Skim before you ship.
Pro Tips
Small habits that pay off every time you reach for this pattern.
leftIndex, rightIndex) to reduce mistakes.Pattern Recognition
Concrete signals that tell you this is the right pattern both at work and on LeetCode.
O(n^2) scans into O(n) or O(n log n) workflows.Practice
A curated easy-to-hard problem ladder. Each one reinforces a specific aspect of the pattern.
| # | Problem | Difficulty | Typical Complexity |
|---|---|---|---|
| 1 | Valid Palindrome | Easy | O(n) |
| 2 | Merge Sorted Array | Easy | O(n+m) |
| 3 | Remove Duplicates from Sorted Array | Easy | O(n) |
| 4 | Two Sum II | Medium | O(n) |
| 5 | Container With Most Water | Medium | O(n) |
| 6 | 3Sum | Medium | O(n^2) |
| 7 | Sort Colors | Medium | O(n) |
| 8 | Trapping Rain Water | Hard | O(n) |
| 9 | Minimum Window Substring | Hard | O(n) |
| 10 | Substring with Concatenation of All Words | Hard | O(n*k) |