🔒 Private Site

This site is password-protected.

Two Ponters Technique

There are 5 major types of two-pointers patterns.

1️⃣ Opposite Direction Pointers (Left + Right)

Array: [4, 7, 9, 12, 15, 20]
         ↑                ↑
         l                r
Opposite-direction pointers

Used mostly when:

Example problems:

Template:

int l = 0, r = n - 1;

while (l < r) {
    // Check condition
    if (arr[l] + arr[r] == target) return true;

    if (arr[l] + arr[r] < target) l++;
    else r--;
}

2️⃣ Sliding Window (Two Pointers in same direction)

Array: [3, 5, 7, 1, 4, 9]
         ↑--------↑
         l        r
Sliding window

Both l and r move forward.

Used when:

You want:

Template:

int l = 0;
for (int r = 0; r < n; r++) {

    // expand window by including arr[r]

    while (window violates condition) {
        // shrink from left
        l++;
    }

    // update answer
}

For more on Sliding Window Click Here

3️⃣ Fast & Slow Pointers (Tortoise & Hare)

Used for:

Template:

ListNode* slow = head;
ListNode* fast = head;

while (fast && fast->next) {
    slow = slow->next;
    fast = fast->next->next;
}

4️⃣ Same Direction but With Gap / K-distance Pointers

Used for:

Example:

Move valid elements forward:

int i = 0;
for (int j = 0; j < n; j++) {
    if (arr[j] != arr[i]) {
        i++;
        arr[i] = arr[j];
    }
}

5️⃣ Two Pointers on Two Arrays

Used for:

Template:

int i = 0, j = 0;
while (i < n && j < m) {
    if (a[i] == b[j]) { ... i++; j++; }
    else if (a[i] < b[j]) i++;
    else j++;
}

⭐ Must Do Problems

Level 1 — Basics

1. Leetcode 125. Valid Palindrome

2. Leetcode 26. Remove Duplicates from Sorted Array

Level 2 — Medium

1. Leetcode 167. Two Sum II - Input Array Is Sorted

2. Leetcode 15. 3Sum

3. Leetcode 11. Container With Most Water

4. Leetcode 31. Next Permutation

Level 3 — Hard

1. Leetcode 42. Trapping Rain Water