dsa / dsa-complexity
20 mins
DSA Module 2: Two Pointers Pattern
Why This Matters: Two pointers technique reduces nested O(N²) array loops down to single-pass O(N) linear time.
## Two Pointers Algorithmic Pattern The **Two Pointers** pattern uses two indices to traverse linear data structures simultaneously. ### Common Variants 1. **Opposite End Pointers**: Left starts at 0, Right starts at N-1 (Palindrome check, Sorted 2-Sum). 2. **Same Direction Pointers**: Fast and Slow pointers (Cycle detection, remove duplicates).
MENTAL MODEL & MEMORY LAYOUT
OPPOSITE-END POINTER TRAVERSAL:
[ L ] ──► 'r' 'a' 'c' 'e' 'c' 'a' 'r' ◄── [ R ]
(left == right -> shrink pointers inward) COMMON PITFALLS TO AVOID
- Forgetting to increment `left += 1` or decrement `right -= 1`, leading to infinite while loops.
Reverse String In-Place
def reverse_string(s: str) -> str:
chars = list(s)
left, right = 0, len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return "".join(chars)
print(reverse_string("hello")) # ollehSwaps characters from outer ends inward in O(N) time and O(1) extra space.
CONCEPT MASTERY CHECKPOINT
Why does the Two Pointers pattern optimize brute-force pair searching from O(N²) to O(N)?
NEXT RECOMMENDED LESSON
DSA Module 3: Sliding Window Pattern
Challenge: Reverse string using two pointers approach.