Back to Journal
Day 4January 18, 2025technicalpatterns

The Pattern That Changed Everything: Two Pointers

M

Marcus A.

Builder of DSA 100 Days

Day 4. Let's get technical.

When I finally understood the Two Pointers pattern - like REALLY understood it - something clicked. Suddenly, maybe 20% of interview problems felt familiar.

What is Two Pointers?

At its simplest: use two indices to traverse a data structure, instead of nested loops.

But that's like saying "addition is combining numbers." Technically true, useless in practice.

Here's what actually matters:

The Three Flavors

1. Opposite Direction (Start/End)

Both pointers start at opposite ends, move toward each other.

When to use it:

  • Sorted arrays
  • Finding pairs with a target sum
  • Palindrome checking
  • Container problems
  • Example: Two Sum in a sorted array

  • Left starts at index 0
  • Right starts at end
  • If sum too small, move left up
  • If sum too big, move right down
  • 2. Same Direction (Fast/Slow)

    Both pointers start at the same position, move at different speeds.

    When to use it:

  • Cycle detection in linked lists
  • Finding middle of linked list
  • Removing duplicates in place
  • Example: Detect cycle in linked list

  • Slow moves one step
  • Fast moves two steps
  • If they meet, there's a cycle
  • 3. Sliding Window (Special Case)

    Technically two pointers, but with specific window semantics.

    When to use it:

  • Substring problems
  • Subarray with conditions
  • Maximum/minimum in a range
  • The Recognition Trick

    When I see a problem, I ask:

    1. Is the input sorted? → Consider start/end pointers

    2. Does it involve a linked list? → Consider fast/slow

    3. Does it mention "subarray" or "substring"? → Consider sliding window

    4. Would brute force be O(n²)? → Two pointers might make it O(n)

    Practice Problems (In Order)

    If you want to master this pattern, do these in order:

    Level 1 (Easy):

  • Two Sum II (sorted array)
  • Valid Palindrome
  • Remove Duplicates from Sorted Array
  • Level 2 (Medium):

  • Container With Most Water
  • 3Sum
  • Linked List Cycle
  • Level 3 (Hard):

  • Trapping Rain Water
  • Minimum Window Substring
  • The Insight That Clicked

    The moment it clicked for me: Two pointers is about **eliminating possibilities efficiently**.

    In Two Sum II, when the sum is too big, you know the right element is too large for ANY element on the left. So you eliminate it. One comparison eliminates n possibilities.

    That's why it's O(n) instead of O(n²).

    Once I understood this core insight, I could apply it to new problems I'd never seen.

    That's the difference between memorizing and understanding.

    Tomorrow: Why I'm building in public and sharing all of this.

    — Marcus

    — Marcus

    Follow the Journey

    New entries every day. Follow on Twitter for real-time updates.