→→

Same Direction Two Pointers

Slow pointer writes valid values; fast pointer scans ahead. Both move left to right — fast races forward while slow only advances when a valid element is found.

Array In-Place Slow / Fast Time O(n) Space O(1)
📋 When to Use
  • Remove duplicates or specific values from a sorted array in-place
  • Partition array: valid elements to front, invalid to back
  • Move zeroes to the end while preserving relative order
  • Count distinct or valid elements without extra memory
  • Need O(1) space — can't copy to a new array
💡 Slow = where to write next valid value. Fast = what to examine next. When fast finds something valid, slow writes it and advances. Duplicate / invalid values are silently skipped by fast.
⚡ Complexity
Time
O(n)
Space
O(1)

Fast pointer visits each element exactly once — O(n) total. Slow pointer never exceeds fast. No auxiliary array needed; modification is in-place with only two integer indices.

Invariant
nums[0..slow] = all unique valid values written so far
Live Animation · Same Direction Pointers · LC #26
Problem — Remove Duplicates from Sorted Array Given a sorted array, remove the duplicates in-place so each unique element appears only once. Return the count of unique elements.
Input: nums = [0, 0, 1, 1, 2, 3, 3]  ·  Answer: 4  (nums becomes [0, 1, 2, 3, _, _, _])
Step 1 / —
🔍 Scan — fast compares, skips duplicates
✍️ Write — slow advances, writes unique value
✅ Done
slow = write pointer (🐢)
fast = scan pointer (🐇)
orange cells = written (valid range)
nums = [0, 0, 1, 1, 2, 3, 3]
slow = 0
fast = 1
unique count = 1
Click ▶ Play or Next ▶ to start
int slow = 0; // write pointer starts at index 0
Complete Java TemplateJAVA
// Two Pointers — Same Direction (Slow/Fast)
int slow = 0;   // write pointer (always behind fast)

for (int fast = 0; fast < nums.length; fast++) {
    if (keep(nums[fast])) {    // condition: not dup, != val, != 0 …
        nums[slow] = nums[fast];
        slow++;
    }
    // else: skip — fast advances, slow waits
}
return slow;   // new length of valid portion
🎯 Practice Problems