← Pointer Manipulation

Micro-Drill #246 — Two pointers: converging vs same-direction

Pointer Manipulation Target: 15s

Converging: start from both ends, narrow down. Same-direction: fast pointer reads, slow pointer writes. Both are O(n).

TWO POINTERS — CONVERGING vs SAME-DIRECTION
────────────────────────────────────────────
CONVERGING (opposite ends → middle):
  l, r = 0, n - 1
  while l < r:
      if condition: l += 1
      else: r -= 1
  → Sorted array: two sum, 3sum, container with most water
  → Palindrome check
  → Partitioning (Dutch national flag)

SAME-DIRECTION (both move forward):
  slow, fast = 0, 0
  while fast < n:
      if condition:
          a[slow] = a[fast]
          slow += 1
      fast += 1
  → Remove duplicates in-place
  → Move zeros to end
  → Linked list: fast/slow for cycle detection, middle

DECISION:
  Sorted + pair sum?     → converging
  Palindrome?            → converging
  Remove/compact?        → same-direction (read/write)
  Cycle in linked list?  → same-direction (fast/slow)
  Merge two sorted?      → same-direction (one per array)

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #245 Micro #247 →