Skip to lesson

Practice: two pointers

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Mastering two pointers means knowing both how to apply it and when to reject it. This practice lesson brings together sorted extremes, read/write deduplication, greedy two-pointer pairing, multi-sum reduction, and the boundary where unsorted index problems require a HashMap instead.

Squares of a sorted array and Remove Duplicates II

When a sorted array contains negative numbers (such as [-4, -1, 0, 3, 10]), their squares form a V-shaped curve: largest at the two outer ends and smallest near zero.

Example 1 · Combining sorted squares and in-place deduplication

SquaresAndDedupDemo.javaJava
import java.util.Arrays;
public class SquaresAndDedupDemo {    // Time: O(n), Space: O(n) for the output array    public static int[] sortedSquares(int[] nums) {        int n = nums.length;        int[] res = new int[n];        int left = 0, right = n - 1, pos = n - 1;        while (left <= right) {            int lSq = nums[left] * nums[left];            int rSq = nums[right] * nums[right];            if (lSq > rSq) {                res[pos--] = lSq;                left++;            } else {                res[pos--] = rSq;                right--;            }        }        return res;    }
    // Time: O(n), Auxiliary Space: O(1)    public static int removeDuplicatesAllowTwo(int[] nums) {        if (nums.length <= 2) return nums.length;        int write = 2;        for (int read = 2; read < nums.length; read++) {            if (nums[read] != nums[write - 2]) {                nums[write++] = nums[read];            }        }        return write;    }
    public static void main(String[] args) {        int[] sq = sortedSquares(new int[]{-3, -3, -3, 1, 3});        System.out.println("Sorted squares:  " + Arrays.toString(sq));        int k = removeDuplicatesAllowTwo(sq);        System.out.println("At most 2 copies: " + Arrays.toString(Arrays.copyOf(sq, k)));    }}
Output
Sorted squares:  [1, 9, 9, 9, 9]
At most 2 copies: [1, 9, 9]

What this code does

  • sortedSquares uses converging pointers to turn [-3, -3, -3, 1, 3] into [1, 9, 9, 9, 9] in O(n) time.
  • removeDuplicatesAllowTwo then uses same-direction read/write pointers to compact [1, 9, 9, 9, 9] to [1, 9, 9] in place.

Converging pointers left = 0 and right = n - 1 compare nums[left] * nums[left] against nums[right] * nums[right] and fill the output array from index n - 1 down to 0 in O(n) time.

When deduplicating a sorted array to allow at most two copies of each value, same-direction read and write pointers start at index 2 and keep nums[read] whenever nums[read] != nums[write - 2], running in O(n) time and O(1) auxiliary space.

  • Sorted Squares: converging pointers (while (left <= right)), filling result from n - 1 down to 0.
  • Remove Duplicates II: same-direction pointers (write = 2, read = 2..n-1), comparing nums[read] != nums[write - 2].

Boats to save people, Three Sum Closest, and Four Sum

In Boats to Save People, each boat carries at most 2 people up to a weight limit.

  1. Sort the array first (O(n log n)).
  2. For Boats to Save People: pair right with left if people[left] + people[right] <= limit, else send right alone.
  3. For 3Sum Closest / 4Sum: fix outer indices, skip duplicates backward (j > start && nums[j] == nums[j - 1]), and sweep left and right.

Example 2 · Boats to Save People: greedy two pointers after sorting

BoatsToSavePeopleDemo.javaJava
import java.util.Arrays;
public class BoatsToSavePeopleDemo {    public static int numRescueBoats(int[] people, int limit) {        Arrays.sort(people);        int left = 0, right = people.length - 1;        int boats = 0;        while (left <= right) {            if (people[left] + people[right] <= limit) {                left++; // Lightest person rides with heaviest            }            right--; // Heaviest person always boards a boat            boats++;        }        return boats;    }
    public static void main(String[] args) {        System.out.println("Boats for [1,2] limit 3:       " + numRescueBoats(new int[]{1, 2}, 3));        System.out.println("Boats for [3,2,2,1] limit 3:   " + numRescueBoats(new int[]{3, 2, 2, 1}, 3));        System.out.println("Boats for [3,5,3,4] limit 5:   " + numRescueBoats(new int[]{3, 5, 3, 4}, 5));    }}
Output
Boats for [1,2] limit 3:       1
Boats for [3,2,2,1] limit 3:   3
Boats for [3,5,3,4] limit 5:   4

What this code does

  • On [3, 2, 2, 1] sorted to [1, 2, 2, 3] with limit = 3: 3 rides alone (right = 2), then 1 + 2 <= 3 ride together (left = 1, right = 1), then the remaining 2 at left == right == 1 boards the 3rd boat.
  • When left == right, the condition people[left] + people[right] <= limit may or may not hold, but right-- and boats++ always terminate the loop cleanly after counting 1 boat for that final person.

After sorting people (O(n log n)), consider the heaviest remaining person at right: if they can share a boat withanyone, they can certainly share with the lightest remaining person at left (people[left] + people[right] <= limit). If people[left] + people[right] <= limit, pair them together (left++; right--;); otherwise the heaviest person must ride alone (right--;). Every step uses 1 boat!

For 3Sum Closest (O(n²)) and 4Sum (O(n³)), sorting lets us fix k - 2 outer indices and sweep converging pointers across the remaining suffix, using long arithmetic in 4Sum to prevent 32-bit overflow.

When two pointers fails: unsorted data with no order to use

Two pointers is not a silver bullet: it fails when the data has no order to use.

Example 3 · When two pointers fails: Unsorted Two Sum returning original indices

UnsortedTwoSumDemo.javaJava
import java.util.Arrays;import java.util.HashMap;import java.util.Map;
public class UnsortedTwoSumDemo {    // Two pointers on unsorted data FAILS because order is not monotonic.    // HashMap solves it in O(n) time and O(n) space while preserving original indices.    public static int[] twoSumUnsortedIndices(int[] nums, int target) {        Map<Integer, Integer> seenIndex = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            int need = target - nums[i];            if (seenIndex.containsKey(need)) {                return new int[]{seenIndex.get(need), i};            }            seenIndex.put(nums[i], i);        }        return new int[]{-1, -1};    }
    public static void main(String[] args) {        int[] nums = {3, 2, 4};        System.out.println("Indices for target 6 in [3,2,4]: " + Arrays.toString(twoSumUnsortedIndices(nums, 6)));    }}
Output
Indices for target 6 in [3,2,4]: [1, 2]

What this code does

  • If we sorted [3, 2, 4] into [2, 3, 4], two pointers would find 2 + 4 = 6 at sorted indices [0, 2], which is the wrong answer for the original array where 2 and 4 sit at [1, 2].
  • Using a HashMap preserves original indices in a single O(n) pass.
  1. Unsorted array where original indices are required (classic: Two Sum): A converging loop on an unsorted array has no monotonic direction to move left or right, and sorting destroys the original indices. Use a HashMap<Integer, Integer> mapping each seen value to its index in O(n) time and O(n) space.
  2. Subarray sum with negative numbers: Moving a pointer forward in an array containing negative numbers can either increase or decrease the running sum, breaking monotonicity.
Always ask before writing a two-pointer loop: 'When my comparison fails, does moving left or right guarantee progress without skipping a valid answer?'

Finish up

Mark complete & continue

Next: The sliding window idea