GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
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")) # olleh

Swaps 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
Continue Path
Challenge: Reverse string using two pointers approach.
DSA Module 2: Two Pointers Pattern
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.