Lesson 15 · Core algorithms

Advanced Two Pointers

The basic patterns move two indexes over one sequence. The harder problems add a third index, an outer loop, or a second array, but the rule stays the same: every move must rule out something for good.

Advanced Two Pointers concept diagramThree panels. First, the sorted values −4, −1, −1, 0, 1, 2 with index i fixed on the first −1 and a left and right pointer converging on the values after it. Second, an array split by low, mid and high into four zones: 0s, 1s, unchecked values, and 2s; mid moves right and high moves left until the unchecked zone is empty. Third, array a holding 1, 4, 7 and three empty slots and array b holding 2, 5, 6: arrows show 7 copied into the last slot and 6 into the slot before it, filling from the back.1 · fix a[i], converge a pair on the rest (3Sum)-4-1-1012ileftrightsum < 0 → left upsum > 0 → right down2 · three pointers, four zones (0s · 1s · unchecked · 2s)0011???22lowmidhigh3 · two arrays: merge from the backa147_67b2567 > 6: 7 to the endthen 6 into slot 4
1

Beyond One Pair

The two pointers lesson covers the three base shapes: converging from both ends, moving in the same direction, and fast and slow. Advanced two pointers problems combine those shapes with one more piece: an outer loop that fixes a value, a third pointer that marks another boundary, or a second array to walk at the same time.

The proof that each version is correct is the same as before. A pointer may move only when the values it skips can never be part of an answer. Check that for every move and the code is right; skip it and the bugs are subtle.

  • Outer loop + pair: 3Sum, 4Sum, closest triple
  • Three boundaries: three-way partitioning
  • Two arrays: merging, intersections
2

Fix One, Sweep the Rest: 3Sum and k Sum

  1. Sort the array.
  2. For each i (skipping a repeat of a[i − 1]): set left = i + 1, right = n − 1.
  3. Sum too small: left += 1. Too big: right −= 1. Zero: record, move both, skip repeats.

To find every triple that sums to zero, sort first, then fix the first value a[i] and look for a pair in the rest that sums to −a[i]. That inner search is the converging pair: if the sum is too small, move left up; if too big, move right down. Each fixed value costs O(n), so the whole search is O(n²), against O(n³) for trying every triple.

On −1, 0, 1, 2, −1, −4, sorted to −4, −1, −1, 0, 1, 2, the answers are [−1, −1, 2] and [−1, 0, 1]. Sorting also handles duplicates: skip a fixed value equal to the one before it, and after a match skip left past equal values. Without those skips [−1, 0, 1] would be reported twice.

The same nesting solves the general k sum problem: k − 2 nested loops around one converging pair give O(n^(k−1)). 4Sum is two loops and a pair; 3Sum Closest keeps the best sum instead of matches.

  • Sorting costs O(n log n), less than the O(n²) search
  • If a[i] > 0 on sorted data, no later triple can reach 0: stop early
  • Practice: 3Sum
3

Three Pointers, Four Zones

The three pointer technique sorts an array of only 0s, 1s and 2s in one pass. low, mid and high split it into four zones: 0s before low, 1s from low to mid − 1, unchecked values from mid to high, 2s after high. Each step looks at a[mid] and shrinks the unchecked zone by one.

A 0 is swapped to low and both low and mid move on. A 1 is already in place, so only mid moves. A 2 is swapped to high and high moves in, but mid stays: the value that came back from high has never been looked at. Moving mid there is the classic bug; on 2, 1, 2 it leaves the array unchanged. This is the Dutch national flag method behind Sort Colors, and quicksort uses the same split to handle many equal keys.

  • Loop while mid ≤ high
  • 0: swap with low, low++ and mid++ · 1: mid++ · 2: swap with high, high-- only
  • One pass, O(1) extra space
Key reference

Terms, operations, and practical uses

Key terms

  • Fixed elementThe value held by the outer loop while a pair searches the rest.
  • ZoneA stretch of the array whose values are already classified.
  • Write pointerWhere the next merged value goes; moves from the back when merging in place.

Related

  • Two pointersConverging, same-direction and fast-slow pointers.
  • Sliding windowWindows that grow and shrink with a condition.
  • Quick sortPartitioning with pointers, including three-way splits.
  • 3SumFix one value, sweep a pair.
  • Sort ColorsThree pointers in one pass.
Implementation

Code in Python, C++ and Java

def three_sum(nums):
    nums = sorted(nums)
    out = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                out.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
    return out


def three_way_partition(a):
    low, mid, high = 0, 0, len(a) - 1
    while mid <= high:
        if a[mid] == 0:
            a[low], a[mid] = a[mid], a[low]
            low += 1
            mid += 1
        elif a[mid] == 1:
            mid += 1
        else:
            a[mid], a[high] = a[high], a[mid]
            high -= 1
    return a


def merge_from_back(a, m, b):
    i, j, w = m - 1, len(b) - 1, m + len(b) - 1
    while j >= 0:
        if i >= 0 and a[i] > b[j]:
            a[w] = a[i]
            i -= 1
        else:
            a[w] = b[j]
            j -= 1
        w -= 1
    return a


print("triplets", three_sum([-1, 0, 1, 2, -1, -4]))
print("partition", three_way_partition([2, 0, 2, 1, 1, 0]))
print("merged", merge_from_back([1, 4, 7, 0, 0, 0], 3, [2, 5, 6]))
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> threeSum(vector<int> nums) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> out;
    int n = nums.size();
    for (int i = 0; i + 2 < n; i++) {
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        int left = i + 1, right = n - 1;
        while (left < right) {
            int total = nums[i] + nums[left] + nums[right];
            if (total < 0) left++;
            else if (total > 0) right--;
            else {
                out.push_back({nums[i], nums[left], nums[right]});
                left++;
                right--;
                while (left < right && nums[left] == nums[left - 1]) left++;
            }
        }
    }
    return out;
}

vector<int> threeWayPartition(vector<int> a) {
    int low = 0, mid = 0, high = (int)a.size() - 1;
    while (mid <= high) {
        if (a[mid] == 0) swap(a[low++], a[mid++]);
        else if (a[mid] == 1) mid++;
        else swap(a[mid], a[high--]);
    }
    return a;
}

vector<int> mergeFromBack(vector<int> a, int m, const vector<int>& b) {
    int i = m - 1, j = (int)b.size() - 1, w = m + (int)b.size() - 1;
    while (j >= 0) {
        if (i >= 0 && a[i] > b[j]) a[w--] = a[i--];
        else a[w--] = b[j--];
    }
    return a;
}

string show(const vector<int>& v) {
    string s = "[";
    for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
    return s + "]";
}

int main() {
    cout << "triplets [";
    auto t = threeSum({-1, 0, 1, 2, -1, -4});
    for (size_t i = 0; i < t.size(); i++) cout << (i ? ", " : "") << show(t[i]);
    cout << "]\n";
    cout << "partition " << show(threeWayPartition({2, 0, 2, 1, 1, 0})) << "\n";
    cout << "merged " << show(mergeFromBack({1, 4, 7, 0, 0, 0}, 3, {2, 5, 6})) << "\n";
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    static List<List<Integer>> threeSum(int[] input) {
        int[] nums = input.clone();
        Arrays.sort(nums);
        List<List<Integer>> out = new ArrayList<>();
        for (int i = 0; i + 2 < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int total = nums[i] + nums[left] + nums[right];
                if (total < 0) left++;
                else if (total > 0) right--;
                else {
                    out.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                }
            }
        }
        return out;
    }

    static int[] threeWayPartition(int[] a) {
        int low = 0, mid = 0, high = a.length - 1;
        while (mid <= high) {
            if (a[mid] == 0) {
                int t = a[low]; a[low++] = a[mid]; a[mid++] = t;
            } else if (a[mid] == 1) {
                mid++;
            } else {
                int t = a[mid]; a[mid] = a[high]; a[high--] = t;
            }
        }
        return a;
    }

    static int[] mergeFromBack(int[] a, int m, int[] b) {
        int i = m - 1, j = b.length - 1, w = m + b.length - 1;
        while (j >= 0) {
            if (i >= 0 && a[i] > b[j]) a[w--] = a[i--];
            else a[w--] = b[j--];
        }
        return a;
    }

    public static void main(String[] args) {
        System.out.println("triplets " + threeSum(new int[] {-1, 0, 1, 2, -1, -4}));
        System.out.println("partition " + Arrays.toString(threeWayPartition(new int[] {2, 0, 2, 1, 1, 0})));
        System.out.println("merged " + Arrays.toString(mergeFromBack(new int[] {1, 4, 7, 0, 0, 0}, 3, new int[] {2, 5, 6})));
    }
}
Watch it run

Step through it

Running on 3Sum [-1, 0, 1, 2, -1, -4] · split [2, 0, 2, 1, 1, 0] · merge [1, 4, 7] + [2, 5, 6]

3Sum · triples that sum to 0i = 0-40-11-12031425ileftrightfound: none yetO(n²): n fixed values × one O(n) pair sweep
Step 1

Sort, then fix one value

To find triples that sum to 0 in −1, 0, 1, 2, −1, −4, sort first: −4, −1, −1, 0, 1, 2. Sorting lets a pair move by rule (too small: go right, too big: go left) and puts equal values next to each other, which makes duplicates easy to skip. The outer loop fixes a[i]; a converging pair searches the rest for −a[i].

Output
1 / 14
4

Two Pointers on Two Arrays

With two pointers on two arrays, each pointer walks its own sorted sequence and the smaller value moves on. That merges two sorted lists, finds their common values, or pairs the closest elements, all in O(n + m).

One twist appears when the first array has empty room at its end for the second: 1, 4, 7, _, _, _ and 2, 5, 6. Merging from the front would write 2 into the slot holding 4 before 4 is read. Merging from the back is safe: compare the last real values, 7 and 6, write the larger into the last slot, and step back. The write pointer never overtakes an unread value, so no extra buffer is needed. Merge Sorted Array is this exact problem.

  • Merge, intersect, compare: advance the pointer at the smaller value
  • Filling in place: start at the back so writes land on empty slots
  • Stop when the second array is used up; the rest of the first is already in place
5

Bounds That Move With Data

In Trapping Rain Water two converging pointers also carry the tallest bar seen from each side. Water over a bar is limited by the lower of the two maxima, so the side with the lower maximum can be settled and its pointer moved. The pointers move by a comparison of running state, not of the values under them.

That is the common thread across this lesson. The pointer rule can depend on a sum, a zone or a running maximum, but there must always be a reason why the skipped values are finished. For windows that grow and shrink with a condition, see sliding window.

  • Running maxima decide which side is safe to settle
  • Every move needs a reason the skipped values are done