Interview ReadyLesson 1 of 3 in Array PatternsFree preview

Two Pointers

Two pointers replaces a nested loop with two indices that each move in one direction, so the whole scan is O(n).

Opposite ends (needs a sorted array). Find a pair with sum target:

int l = 0, r = n - 1;
while (l < r) {
    int s = a[l] + a[r];
    if (s == target) return true;
    if (s < target) l++;   // need a bigger sum
    else r--;              // need a smaller sum
}

This works only because the array is sorted: moving l right can only increase the sum, and moving r left can only decrease it. On an unsorted array, use a hash set instead.

Same direction (slow and fast). fast scans every element; slow marks where the next "kept" element goes. Removing duplicates from a sorted array in place:

int k = 0;
for (int i = 0; i < n; i++)
    if (k == 0 || a[i] != a[k - 1]) a[k++] = a[i];
// a[0..k-1] now holds the unique values

Other classics: reverse an array, merge two sorted arrays, container with most water, 3Sum (sort, fix one element, two-pointer the rest: O(n²)).

In interviews: say the brute force (O(n²) pairs) first, then explain why each pointer move is safe. That reasoning is what the interviewer is checking.

Practice

Solve 3 of 4 to complete this lesson.

0/4 solved

Solve 3 more to complete this lesson, or move on and come back later.

Skip to next: Sliding Window