DSA — Techniques
Two Pointer
Use two indices moving toward each other or in the same direction to solve pair/subarray problems in O(n) instead of O(n²).
O(n)Time
O(1)Space
SortedArrays
PairProblems
✓Slide+Shrink
// TWO SUM II — SORTED ARRAY
Find two numbers that sum to target
How It Works
Python Code
Use Cases
Quiz
Practice
01
Sort
Array must be sorted (or use hash map for unsorted).
arr.sort()
02
lo=0, hi=n-1
Start pointers at opposite ends.
lo, hi = 0, len(arr)-1
03
Check Sum
If sum too small → lo++. Too large → hi--.
if total < target: lo += 1
04
Found!
When sum equals target — return both indices.
return [lo, hi]
python
def two_sum_sorted(arr, target): lo, hi = 0, len(arr) - 1 while lo < hi: total = arr[lo] + arr[hi] if total == target: return [lo, hi] elif total < target: lo += 1 else: hi -= 1 return []
Opposite ends:
Two Sum, 3-Sum, Container with most water, Trapping rain water.
Same direction: Remove duplicates, sliding window, fast-slow pointer (cycle detection).
Same direction: Remove duplicates, sliding window, fast-slow pointer (cycle detection).
Two Sum
3-Sum
Trapping Rain Water
Container With Most Water
Valid Palindrome
Remove Duplicates
Two Pointer reduces O(n²) to O(n) because:
Progress
0 / 6 solved
6 problems · 5 PBC · 1 Startup
#001
Two Sum II (Sorted)
Google
PBC
→
#007
3 Sum
Amazon, Adobe
PBC
→
#008
Trapping Rain Water
Google
PBC
→
#010
Container With Most Water
Google, Meta
PBC
→
#028
Valid Palindrome
Amazon
PBC
→
#017
Merge Sorted Arrays
Cure.fit
STARTUP
→