Two Pointers
The Two Pointers Pattern
Two indices walk the same array, usually from opposite ends toward each other or at different speeds. Each step, one pointer moves based on a comparison, so the pair sweeps the whole search space in a single pass instead of checking every combination.
Interactive problems
Free to open
How do you recognise a two pointers problem?
The array is sorted, or sorting it does not lose information, and the question asks for a pair or triplet meeting some condition. "Find two numbers that sum to X", "the container holding the most water", "remove duplicates in place" are all this pattern. If your first instinct is a nested loop over the same array, check whether two pointers collapses it.
What is the time complexity of the two pointers pattern?
O(n) time and O(1) extra space, against O(n²) for the nested-loop version. When sorting is required first, the sort dominates at O(n log n).
Two Pointers practice problems
Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.
Two Pointers problems by difficulty and complexity
The difficulty, running time and extra space of every two pointers solution on this page, as each lesson derives them.
| Lesson | Difficulty | Best | Average | Worst | Space |
|---|---|---|---|---|---|
| Introduction to Two Pointers | Easy | Ω(1) | Θ(n) | O(n) | O(1) |
| Two Sum II - Input Array Is Sorted | Medium | Ω(1) | Θ(n) | O(n) | O(1) |
| Valid Palindrome | Easy | Ω(1) | Θ(n) | O(n) | O(1) |
| Longest Palindromic Substring | Medium | Ω(n) | O(n²) | O(n²) | O(1) |
| Container With Most Water | Medium | Ω(n) | Θ(n) | O(n) | O(1) |
| 3-Sum | Medium | Ω(n²) | Θ(n²) | O(n²) | O(log n) |
| Valid Triangle Number | Medium | Ω(n²) | Θ(n²) | O(n²) | O(log n) |
| Move Zeroes | Easy | Ω(n) | Θ(n) | O(n) | O(1) |
| Sort Colors | Medium | Ω(n) | Θ(n) | O(n) | O(1) |
| Trapping Rain Water | Hard | Ω(n) | Θ(n) | O(n) | O(1) |
Related patterns and concepts
The underlying technique is covered from first principles in the two pointers lesson in the DSA visualizer curriculum. Two Pointers is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.
Every other coding interview pattern
Depth-First Search · 25 lessons
- Introduction to DFSFree
- DFS FundamentalsFree
- Return Values in DFS
- Invert Binary Tree
- Maximum Depth of Binary Tree
- Path Sum
- Passing Values Down (State)
- Validate Binary Search Tree
- Kth Smallest Element in a BST
- Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Tilt
- Diameter of Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Path Sum II
- Longest Univalue Path
- Graphs Overview
- Graph Representation: Adjacency List
- Clone Graph
- Graph Valid Tree
- Matrices as Graphs
- Flood Fill
- Types of DFS (Tree Traversals)
- Number of Islands
- Surrounded Regions
- Pacific Atlantic Water FlowFree
