Two Pointers
The Pattern That Turns O(n²) Into O(n)

Documenting the journey of understanding DSA patterns — focusing on clarity, not memorization.
Why Do We Even Need Two Pointers?
When we first learn arrays, our brain naturally jumps to nested loops.
Want to find a pair?
Use two loops.
Want to compare elements?
Two loops.
Works? Yes.
Efficient? Not really.
If an array has 10,000 elements, O(n²) means 100 million comparisons. That’s… unnecessary suffering.
This is where the Two Pointers pattern quietly saves the day.
What Is the Two Pointers Pattern?
Instead of scanning the array again and again, we use two indices to traverse it intelligently.
There are two main styles:
Opposite Direction Pointers (Left–Right)
When to Use
Sorted array
Finding a pair
Palindrome / symmetry
Shrinking search space
Generic Java Template
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (condition(arr[left], arr[right])) {
// required action
left++;
right--;
} else if (needToIncreaseSomething) {
left++;
} else {
right--;
}
}
Why It Works
Since the array is sorted (in most cases), you can:
Move left → increase value
Move right → decrease value
No nested loops. Just one pass.
Time: O(n)
Space: O(1)
Same Direction Pointers (Slow–Fast)
When to Use
Remove duplicates
Move zeroes
In-place modification
Compact valid elements
Generic Java Template
int slow = 0;
for (int fast = 0; fast < arr.length; fast++) {
if (condition(arr[fast])) {
arr[slow] = arr[fast];
slow++;
}
}
Fast → scans the array
Slow → keeps track of correct placement
Again, single traversal.
Time: O(n)
Space: O(1)
How to Recognize Two Pointers Quickly
Look for keywords like:
“Sorted array”
“Find a pair”
“Palindrome”
“In-place”
“Remove duplicates”
“Two elements”
“Subarray boundaries”
Whenever you feel tempted to write two loops, pause and ask:
Can I solve this by moving boundaries instead?
Most of the time, yes.
Practice Questions (LeetCode)
Start from basic → then move to slightly tricky ones.
Two Sum II - Input Array Is Sorted
Classic opposite direction pointers.Valid Palindrome
Simple symmetry check using left–right.Container With Most Water
Boundary shrinking logic.Remove Duplicates from Sorted Array
Slow–fast pointer classic.Move Zeroes
Compact valid elements.3Sum
Sorting + Two Pointers combo.Squares of a Sorted Array
Opposite direction trick.Sort Colors
Partitioning with pointers.Minimum Size Subarray Sum
Leads toward Sliding Window.Boats to Save People
Greedy + Two Pointers mix.
Final Takeaway
Two Pointers isn’t just a trick.
It trains you to:
Use structure (like sorting)
Reduce unnecessary comparisons
Think in terms of boundaries
And once that thinking develops, nested loops start feeling unnecessary.
