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
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))); }}Sorted squares: [1, 9, 9, 9, 9] At most 2 copies: [1, 9, 9]
What this code does
sortedSquaresuses converging pointers to turn[-3, -3, -3, 1, 3]into[1, 9, 9, 9, 9]in O(n) time.removeDuplicatesAllowTwothen uses same-directionread/writepointers 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)), fillingresultfromn - 1down to0. - Remove Duplicates II: same-direction pointers (
write = 2, read = 2..n-1), comparingnums[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.
- Sort the array first (O(n log n)).
- For Boats to Save People: pair
rightwithleftifpeople[left] + people[right] <= limit, else sendrightalone. - For 3Sum Closest / 4Sum: fix outer indices, skip duplicates backward (
j > start && nums[j] == nums[j - 1]), and sweepleftandright.
Example 2 · Boats to Save People: greedy two pointers after sorting
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)); }}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]withlimit = 3:3rides alone (right = 2), then1 + 2 <= 3ride together (left = 1, right = 1), then the remaining2atleft == right == 1boards the 3rd boat. - When
left == right, the conditionpeople[left] + people[right] <= limitmay or may not hold, butright--andboats++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
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))); }}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 find2 + 4 = 6at sorted indices[0, 2], which is the wrong answer for the original array where2and4sit at[1, 2]. - Using a
HashMappreserves original indices in a single O(n) pass.
- Unsorted array where original indices are required (classic: Two Sum): A converging loop on an unsorted array has no monotonic direction to move
leftorright, and sorting destroys the original indices. Use aHashMap<Integer, Integer>mapping each seen value to its index in O(n) time and O(n) space. - 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.
left or right guarantee progress without skipping a valid answer?'Finish up
Mark complete & continue
Next: The sliding window idea