🧠 The "Two Pointers" Cheat Sheet: Master 25+ Problems with Just ONE Pattern

🧠 The "Two Pointers" Cheat Sheet: Master 25+ Problems with Just ONE Pattern

🔥 Why This Post Will Change Your LeetCode Game

Stop solving problems randomly. Start recognizing patterns. Two Pointers is the most underrated pattern that appears in 100+ LeetCode problems, yet most people don't know when to use it.

After solving 500+ problems, I've broken down the Two Pointers Pattern into 5 categories that will make you spot these problems instantly in interviews.


📊 Pattern Categories

1️⃣ Opposite Direction (Left & Right)

When to use: Array/String manipulation, partition problems, palindrome checks

Template:

int left = 0, right = n - 1;
while (left < right) {
    // Process based on condition
    if (condition) {
        // Do something
    }
    left++;
    right--;
}

Problems:

  • ✅ Two Sum II (LC 167) - Easy
  • ✅ Container With Most Water (LC 11) - Medium
  • ✅ Valid Palindrome (LC 125) - Easy
  • ✅ 3Sum (LC 15) - Medium
  • ✅ Trapping Rain Water (LC 42) - Hard
  • ✅ Sort Colors (LC 75) - Medium

2️⃣ Same Direction (Fast & Slow)

When to use: Remove duplicates, in-place modifications, linked list cycles

Template:

int slow = 0;
for (int fast = 0; fast < n; fast++) {
    if (condition) {
        arr[slow] = arr[fast];
        slow++;
    }
}

Problems:

  • ✅ Remove Duplicates (LC 26) - Easy
  • ✅ Move Zeroes (LC 283) - Easy
  • ✅ Remove Element (LC 27) - Easy
  • ✅ Linked List Cycle (LC 141) - Easy
  • ✅ Find Duplicate Number (LC 287) - Medium

3️⃣ Sliding Window (Dynamic Fast)

When to use: Subarray/substring problems with constraints

Template:

int left = 0;
for (int right = 0; right < n; right++) {
    // Expand window
    while (window_invalid) {
        // Shrink window
        left++;
    }
    // Update result
}

Problems:

  • ✅ Longest Substring Without Repeating (LC 3) - Medium
  • ✅ Minimum Window Substring (LC 76) - Hard
  • ✅ Max Consecutive Ones III (LC 1004) - Medium
  • ✅ Fruits Into Baskets (LC 904) - Medium
  • ✅ Longest Repeating Character Replacement (LC 424) - Medium

4️⃣ Merge Pattern (Two Arrays)

When to use: Merge sorted arrays, intersection problems

Template:

int i = 0, j = 0;
while (i < n && j < m) {
    if (arr1[i] < arr2[j]) i++;
    else if (arr1[i] > arr2[j]) j++;
    else { /* found match */ i++; j++; }
}

Problems:

  • ✅ Merge Sorted Array (LC 88) - Easy
  • ✅ Intersection of Two Arrays (LC 349) - Easy
  • ✅ Merge Two Sorted Lists (LC 21) - Easy
  • ✅ Partition Labels (LC 763) - Medium

5️⃣ Partition Pattern (Quick Select)

When to use: Partitioning based on condition, Dutch National Flag

Template:

int boundary = 0;
for (int i = 0; i < n; i++) {
    if (condition) {
        swap(arr[i], arr[boundary]);
        boundary++;
    }
}

Problems:

  • ✅ Sort Array By Parity (LC 905) - Easy
  • ✅ Sort Colors (LC 75) - Medium
  • ✅ Partition Array (LC 2161) - Medium
  • ✅ Kth Largest Element (LC 215) - Medium

🎯 The Decision Tree: Which Pattern to Use?

Is it about subarrays/substrings with size/sum constraints?
├─ YES → Sliding Window (Category 3)
└─ NO
Do you have TWO different arrays/lists to process?
├─ YES → Merge Pattern (Category 4)
└─ NO
Do you need to partition/rearrange based on condition?
├─ YES → Partition Pattern (Category 5)
└─ NO
Are pointers moving TOWARD each other?
├─ YES → Opposite Direction (Category 1)
└─ NO → Same Direction / Fast-Slow (Category 2)

🚀 Interview Scenarios

Scenario 1: "Find pair with target sum in sorted array"

Instant Recognition: Sorted array + pair → Opposite Direction

// Two Sum II approach
int left = 0, right = n - 1;
while (left < right) {
    int sum = arr[left] + arr[right];
    if (sum == target) return true;
    else if (sum < target) left++;
    else right--;
}

Scenario 2: "Remove all occurrences in-place"

Instant Recognition: In-place + modify → Same Direction (Fast-Slow)

int slow = 0;
for (int fast = 0; fast < n; fast++) {
    if (arr[fast] != val) {
        arr[slow++] = arr[fast];
    }
}

Scenario 3: "Longest substring with at most K distinct characters"

Instant Recognition: Substring + constraint → Sliding Window

unordered_map<char, int> freq;
int left = 0, maxLen = 0;
for (int right = 0; right < n; right++) {
    freq[s[right]]++;
    while (freq.size() > k) {
        freq[s[left]]--;
        if (freq[s[left]] == 0) freq.erase(s[left]);
        left++;
    }
    maxLen = max(maxLen, right - left + 1);
}

💎 Pro Tips That Took Me 6 Months to Learn

  1. Sorted Array = Strong Two Pointers Signal

    • 90% of sorted array problems use two pointers
  2. "In-Place" = Fast-Slow Pattern

    • If they say "O(1) space", think fast-slow
  3. Subarray/Substring = Sliding Window

    • "Longest/shortest" + "subarray/substring" = sliding window
  4. Multiple Arrays = Merge Pattern

    • Processing 2+ sorted arrays together
  5. Partition/Rearrange = Quick Select Style

    • Moving elements based on conditions

🎓 Practice Roadmap (30 Days to Mastery)

Week 1: Opposite Direction (10 problems)

  • Day 1-2: Two Sum II, Container With Most Water
  • Day 3-4: Valid Palindrome, Reverse String
  • Day 5-7: 3Sum, 4Sum, Sort Colors

Week 2: Same Direction (8 problems)

  • Day 8-9: Remove Duplicates, Move Zeroes
  • Day 10-12: Linked List Cycle, Find Duplicate
  • Day 13-14: Squares of Sorted Array

Week 3: Sliding Window (8 problems)

  • Day 15-17: Longest Substring, Max Consecutive Ones
  • Day 18-20: Minimum Window Substring
  • Day 21: Sliding Window Maximum

Week 4: Mixed Practice (4 problems)

  • Day 22-25: Merge intervals, Partition problems
  • Day 26-30: Mock interviews with random problems

🔥 Common Mistakes to Avoid

Mistake 1: Using two pointers when you need a hash map

  • Problem: "Two Sum" in unsorted array
  • Wrong: Two pointers | Right: Hash map

Mistake 2: Not handling edge cases

// Always check:
if (n == 0 || n == 1) return /* base case */;

Mistake 3: Wrong pointer movement

  • Left pointer should only move right
  • Right pointer should only move left
  • Don't cross them randomly

Mistake 4: Forgetting to validate while condition

// Always ensure valid range
while (left < right) // not left <= right for opposite direction
while (slow < n && fast < n) // for same direction

📈 Complexity Cheat Sheet

PatternTimeSpaceBest For
Opposite DirectionO(n)O(1)Sorted array, palindrome
Same DirectionO(n)O(1)In-place modification
Sliding WindowO(n)O(k)Subarray with constraint
MergeO(n+m)O(1)Two sorted arrays
PartitionO(n)O(1)Rearrange elements

🎯 Interview Red Flags (When NOT to Use Two Pointers)

🚫 Unsorted array + need all pairs → Use Hash Map
🚫 Need to find elements in any order → Use Hash Set
🚫 Tree/Graph traversal → Use DFS/BFS
🚫 Dynamic Programming state → Use DP array
🚫 Need frequency count → Use Hash Map first


💬 Let's Discuss!

  1. Which category do you find hardest?
  2. What's your favorite two-pointer problem?
  3. Any problems I missed that should be here?

Drop your pattern recognition tips below! 👇


🌟 Bonus: Company-Wise Distribution

Google: Loves Sliding Window (40% of array problems)
Amazon: Mix of all patterns (35% two pointers)
Microsoft: Fast-Slow for in-place (30%)
Facebook: Opposite direction for optimization (45%)


If this helped you, give it an upvote! 🚀

Comments (1)