What is the Two Pointers Technique?
Patterns·6 min·Python code
Two pointers uses two indices to scan an array or string in one pass. That replaces an O(n²) nested loop with O(n) time and O(1) extra space.
Two Indices That Replace Nested Loops
Nested loops compare every element with every other element, which costs O(n²). Pointer scans keep two indices and move them by a rule, so you visit every position about once.
Every pointer moves in one direction and never backtracks. Steps stay capped by the array length, which gives you a linear scan in place of a quadratic brute force.
Position of the second pointer stores what you already ruled out. You never rescan the array to ask what pairs with index i.
Opposite Ends and Same Direction Pointers
Converging pointers start at index 0 and the last index, then walk toward one another until they meet. Pair sum on sorted arrays, in place reversal and palindrome checks all use this shape.
Same direction pointers start near the front and advance under different conditions. Slow pointers mark where the next kept value goes, while a scanning pointer reaches ahead to find it, which removes duplicates or zeros in place.
Cycle detection in a linked list uses the same shape. One pointer takes two steps while the other takes one, and they meet only when a cycle exists, which is Floyd's algorithm.
Watching both indices move shows which shape a problem needs.
Why Two Pointers Works on Sorted Arrays
Sorted order tells you which pointer to move. When the two ends sum to less than the target, only the left pointer moving right can raise the sum, and when the sum is too big only the right pointer moving left can lower it.
Every comparison discards one candidate for good, so one pass is enough.
Sorting first with sorting algorithms costs O(n log n) and still pays off for problems like 3Sum, where you fix one value and sweep the rest from both ends. Unsorted data without that structure calls for a hash table instead.
Apply the pattern on CodeStory's array practice problems.
Two Pointers Code Example in Python
def two_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
current = nums[left] + nums[right]
if current == target:
return [left, right]
if current < target:
left += 1 # sum too small, need a larger value
else:
right -= 1 # sum too big, need a smaller value
return [-1, -1] # no pair found
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Two Pointers Time and Space Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
One scan costs O(n) time and O(1) space because neither pointer backtracks. Sorting first adds O(n log n), which then dominates. Nested variants like 3Sum cost O(n²).
Watch Two Pointers Step by Step
Seeing both indices move on your own input shows which pointer to advance. Follow either of these one step at a time.
When to Use Two Pointers
- Searching a sorted array for a pair or triplet that meets a sum or difference condition.
- Reversing an array or string in place or checking a palindrome.
- Removing duplicates, zeros or unwanted values from a sorted array in place.
- Finding a linked list cycle or midpoint with pointers that move at different speeds.
Mistakes to Avoid
- Using the converging sum trick on unsorted data, because the move left or move right logic needs order and sorting first adds O(n log n).
- Getting the loop condition wrong, like left <= right when a value must not pair with itself, or moving the wrong pointer, which causes infinite loops or missed answers.
- Forgetting to skip duplicate values in 3Sum, which returns repeated result tuples.
Two Pointers FAQs
Is two pointers hard to learn?
No. Two indices that never backtrack make the pattern approachable, and it clicks once you see them move. Recognising which problems need it is the harder part, and practice fixes that.
When should I use two pointers instead of a hash table?
Use two pointers when data is sorted or you need O(1) extra space, like in place reversal or deduplication. Use a hash table when input is unsorted and O(n) memory is fine. Two Sum on an unsorted array suits a hash map, and on a sorted array pointers save space.
What is the time complexity of two pointers?
One scan costs O(n) time and O(1) space because every pointer crosses the array at most once. Sorting first makes the total O(n log n), and nested variants like 3Sum cost O(n²).
What is the difference between two pointers and sliding window?
Sliding window is a pointer technique where both pointers move in one direction and the span between them is a contiguous subarray or substring. Plain pointer scans are broader, since indices can start at opposite ends and converge. Tracking a moving window like a max sum or longest substring means sliding window.
Does two pointers need a sorted array?
Converging pair sum needs sorted input, because order tells you which pointer to move. Palindrome checks, in place reversal and cycle detection need no sorting.
Which problems use two pointers?
Pair sum on a sorted array, 3Sum, container with most water, palindrome checks, in place reversal, duplicate removal and linked list cycle detection all fit the pattern.
How do I practise two pointers on CodeStory?
Watch pair sum and container with most water move in CodeStory's visualisers, then write the code yourself in the CodeStory app.
Related Guides
Guides are step one. In a CodeStory batch you code the pointer moves yourself, then explain every step in a scored mock round.
Talk to a Mentor