Two Pointers

Two Pointers

1. Two Pointers start at two ends

(1) Mostly used in sorted array, typical example is K Sum problem

2. Two Pointers start at the same end

(1) Cycle Detection algorithm (pointers move at different paces)

Idea: Define two pointers: fast pointer and slow pointer. if the cycle exists, find the place they meet in the first time. Then move slow pointer to the place it was in the beginning, and both pointer move at the same pace. The cycle starts at the place where these two pointers meet again(How to prove it?). Example: Find the Duplicate Number

public int findDuplicate(int[] nums) {    
        int fast = 0, slow = 0;

        do {
            fast = nums[nums[fast]];
            slow = nums[slow];
        }
        while (fast != slow);

        // Move slow pointer to the beginning
        slow = 0;

        while (fast != slow) {
            fast = nums[fast];
            slow = nums[slow];
        }
        // Cycle starts at the place where two pointers meet
        return slow;
}

(2) Sliding Window (update start pointer when constraints is violated)

Idea: HashTable + Two Pointers

  1. Find the window that contains all character in a substring. Example: Find All Anagrams in a String

  1. Window that contains at most K distinct character. Example: Longest Substring with At Most K Distinct Characters

3. Questions Category

Last updated

Was this helpful?