Home
DSA Patterns
Two Pointers
Introduction to Two Pointers
Introduction to Two Pointers
A space-efficient technique to traverse arrays and strings using two reference points significantly reducing time complexity.
Examples
Because nums[0] + nums[1] == 9, we return [0, 1].
What is the Two Pointer Technique?
The Two Pointer technique is a fundamental strategy where you use two separate reference points (pointers) to traverse a data structure, usually an array or a string.
Instead of using a single loop to scan elements one by one (or nested loops to check every pair), we use two pointers to process information from different positions simultaneously. By moving these pointers based on specific conditions, we can solve problems much faster. This simple trick often turns a slow O(n^2) brute-force solution into an efficient O(n) linear solution.
The Motivation: Two Sum (Sorted)
Now, let's look at a classic problem to see why this technique is so useful.
"Given a sorted array of integers, find two numbers that sum up to a specific
target."
Example:
- Input:
nums = [1, 3, 4, 6, 8, 10, 13] - Target:
13 - Goal: Find two numbers that add to 13. (Answer: 3 + 10)
Attempt 1: Brute Force (Why it fails)
Your first instinct might be to check every single pair.
"Okay, let's try 1+3, 1+4, 1+6... then 3+4, 3+6..."
While this gives the correct answer, it is extremely inefficient.
- Time Complexity: O(n^2). For an array of 10,000 items, that's 100 million checks!
- The Issue: You are doing repetitive work and ignoring the most important clue: The array is sorted.
Visualizing the Brute Force Approach
Switch the figure further down to Check every pair to watch this: the nested loop computes sum after sum, most of which the sorted order could have ruled out.
When should I use Two Pointers?
Pattern Recognition Triggers:
In an interview, consider this pattern immediately if you see:
- Sorted Input: The problem mentions a "sorted array" or implies you can sort it.
- Pair/Triplet Search: You need to find sets of elements (pairs, triplets).
- Minimize/Maximize: You need to find a pair with min/max distance or sum.
- Opposite Ends: The logic suggests checking extremes (smallest vs largest).
The Intuition: Process of Elimination
Let's work smarter, not harder.
Instead of blindly checking pairs, let's use the sorted order to eliminate wrong answers.
Key Insight:
If the sum of our current pair is Too Big, keeping the larger number is useless. It will always trigger a "Too Big" result with any other number. So, we can permanently discard (eliminate) the larger number.
Interactive Walkthrough
TARGET 13 · SORTED
CHECK PAIR
i
0
j
1
2
3
4
5
6
Checks
1
Sum
4
Target
13
nums[0] + nums[1] = 1 + 3 = 4: not 13
Next
nums[0] + nums[2] = 1 + 4 = 5: not 13
Sorted array
Target
Legend & Complexity
The pair being added: i and j, or L and R
The pair that sums to the target
Two pointers: values already ruled out
Pointers are named above their cells
Check every pair
O(n²)
Two pointers
O(n)
Space
O(1)
Compare the two methods on the same array: Check every pair tries sums one by one, while Two pointers moves one pointer per sum and rules out every pair it passes. Checks counts the sums each computes.
Dry Run Table
| Step | Left Pointer (val) | Right Pointer (val) | Sum | Action |
|---|---|---|---|---|
| 1 | Index 0 (1) | Index 6 (13) | 14 | > 13. Too big. Move Right -- |
| 2 | Index 0 (1) | Index 5 (10) | 11 | < 13. Too small. Move Left ++ |
| 3 | Index 1 (3) | Index 5 (10) | 13 | == 13. Found it! Return True |
The Solution Template
The two-pointer loop: compare the pair’s sum with the target and move the pointer that can bring it closer.
Introduction to Two Pointers Code
1function twoSum(nums, target) {2 let left = 0;3 let right = nums.length - 1;45 while (left < right) {6 let sum = nums[left] + nums[right];7 if (sum === target) return true;8 else if (sum < target) left++;9 else right--;10 }11 return false;12}
Edge Cases & Common Mistakes
Edge Case Checklist:
- Empty Array: Return false/empty immediately.
- One Element: Loop condition
left < righthandles this naturally (won't run). - No Solution: Ensure you handle the return value after the loop finishes.
Common Mistakes:
- Not Sorting: The opposite-ends pair search only works on a sorted array. If the input is unsorted, sort it first (O(n log n)), or use a hash map when the original indices matter.
- Wrong Loop Condition: Use
left < rightfor pairs. Useleft <= rightonly if a single element can be the answer.
Summary
Recap:
- The Trick: Use sorted order to eliminate pairs.
- Movement: Sum too small → Increase
left. Sum too big → Decreaseright. - Efficiency: We turned a slow O(n^2) search into a blazing fast O(n) scan.
