Pair sum in a sorted array
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Given a sorted array nums and a target integer, finding two numbers that add up to target takes O(n²) with nested loops or O(n) space with a HashSet. Because the array is sorted, two pointers starting at the ends can find the pair in O(n) time and O(1) space.
Move left or right by comparing
Place left = 0 at the smallest value and right = nums.length - 1 at the largest value. At each step while left < right, compute long sum = (long) nums[left] + nums[right] (using long prevents 32-bit overflow when elements sit near Integer.MAX_VALUE).
- Initialize
left = 0andright = nums.length - 1. - Loop
while (left < right)and computesum = (long) nums[left] + nums[right]. - If
sum == target, return the indices or values. - If
sum < target, incrementleft++; otherwise decrementright--.
Find two numbers that add up to 10
Step 1 of 6
- target
- 10
left on the smallest value and right on the largest. The bar under the cells shows the part of the array still in play.Example 1 · Brute force: try every pair (O(n²) time, O(1) space)
import java.util.Arrays;
public class PairSumBrute { public static int[] twoSumBrute(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{-1, -1}; }
public static void main(String[] args) { int[] nums = {2, 7, 11, 15}; System.out.println("Target 9: " + Arrays.toString(twoSumBrute(nums, 9))); System.out.println("Target 22: " + Arrays.toString(twoSumBrute(nums, 22))); System.out.println("Target 10: " + Arrays.toString(twoSumBrute(nums, 10))); }}Target 9: [0, 1] Target 22: [1, 3] Target 10: [-1, -1]
What this code does
- The two loops test every pair once, about n × n / 2 additions. Nothing is stored, so extra space is O(1).
- The inner loop is really asking one question: "is
target - nums[i]somewhere to my right?" Because the array is sorted, that question can be answered much faster than by scanning.
Example 2 · Better: binary search for the partner (O(n log n) time, O(1) space)
import java.util.Arrays;
public class PairSumBinarySearch { public static int[] twoSumBinarySearch(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { int need = target - nums[i]; int lo = i + 1; int hi = nums.length - 1; while (lo <= hi) { int mid = (lo + hi) >>> 1; if (nums[mid] == need) { return new int[]{i, mid}; } else if (nums[mid] < need) { lo = mid + 1; } else { hi = mid - 1; } } } return new int[]{-1, -1}; }
public static void main(String[] args) { int[] nums = {2, 7, 11, 15}; System.out.println("Target 9: " + Arrays.toString(twoSumBinarySearch(nums, 9))); System.out.println("Target 22: " + Arrays.toString(twoSumBinarySearch(nums, 22))); System.out.println("Target 10: " + Arrays.toString(twoSumBinarySearch(nums, 10))); }}Target 9: [0, 1] Target 22: [1, 3] Target 10: [-1, -1]
What this code does
- For each
nums[i], binary search looks fortarget - nums[i]on its right in O(log n) steps instead of scanning O(n) elements. - It is faster than brute force because sorted order lets each search throw away half of the remaining range. It still repeats one search per element, which the next version avoids.
Example 3 · Optimal: two pointers from both ends (O(n) time, O(1) space)
import java.util.Arrays;
public class PairSumSortedDemo { public static int[] twoSumSorted(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left < right) { long sum = (long) nums[left] + nums[right]; if (sum == target) { return new int[]{left, right}; } else if (sum < target) { left++; } else { right--; } } return new int[]{-1, -1}; }
public static void main(String[] args) { int[] nums = {2, 7, 11, 15}; System.out.println("Target 9: " + Arrays.toString(twoSumSorted(nums, 9))); System.out.println("Target 22: " + Arrays.toString(twoSumSorted(nums, 22))); System.out.println("Target 10: " + Arrays.toString(twoSumSorted(nums, 10))); }}Target 9: [0, 1] Target 22: [1, 3] Target 10: [-1, -1]
What this code does
- For
target = 22on[2, 7, 11, 15]: first2 + 15 = 17 < 22(leftmoves to1), then7 + 15 = 22, returning[1, 3]. - Casting
nums[left]tolongbefore addition prevents integer overflow when values are close toInteger.MAX_VALUE. - Why it is faster: each comparison rules out a whole row or column of pairs, so the pointers only walk inward and meet after at most n steps. No search is repeated.
Now compare sum against target:
- If
sum == target, we found the pair(left, right). - If
sum < target, the current sum is too small. Sincenums[right]is already the largest remaining value,nums[left]cannot possibly reachtargetwith any element inleft..right. We incrementleft++to pick a larger left number. - If
sum > target, the current sum is too large. Sincenums[left]is already the smallest remaining value,nums[right]cannot possibly reachtargetwith any element inleft..right. We decrementright--to pick a smaller right number.
Order of execution
Order one pass of the pair-sum loop
Tap the steps in the order the loop runs them.
Why no valid pair is skipped (proof sketch)
Interviewers often ask: 'How do you know incrementing left or decrementing right never skips the true answer pair `(i, j) with i < j`?'
Suppose a valid pair (i*, j*) exists such that nums[i*] + nums[j*] == target. Since left starts at 0 <= i* and right starts at n - 1 >= j*, one of the two pointers must reach its target index (left == i* or right == j*) first.
Take the case where left reaches i* first while right is still strictly to the right of j* (right > j*). Because the array is sorted in non-decreasing order, nums[right] >= nums[j*]. If nums[right] == nums[j*], then (i*, right) already sums to target and we immediately succeed! If nums[right] > nums[j*], then nums[i*] + nums[right] > nums[i*] + nums[j*] = target. Our rule sees sum > target and decrements right--, leaving left parked safely at i* until right walks down to j*!
left++ rules out (left, k) for all k <= right) or an entire column (right-- rules out (k, right) for all k >= left) of the n × n pair grid.Counting all pairs and handling duplicates
When the problem asks for all pairs that sum to target instead of stopping at the first match, what you do on sum == target depends on whether the array has duplicates and whether the question wants unique value pairs or index pairs.
Example 4 · Listing all unique value pairs that sum to target (skipping duplicates)
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class UniquePairsDemo { public static List<String> uniqueValuePairs(int[] nums, int target) { List<String> pairs = new ArrayList<>(); int left = 0, right = nums.length - 1; while (left < right) { long sum = (long) nums[left] + nums[right]; if (sum == target) { pairs.add("(" + nums[left] + ", " + nums[right] + ")"); left++; right--; while (left < right && nums[left] == nums[left - 1]) left++; while (left < right && nums[right] == nums[right + 1]) right--; } else if (sum < target) { left++; } else { right--; } } return pairs; }
public static void main(String[] args) { int[] nums = {1, 1, 2, 2, 3, 4, 4, 5}; System.out.println("Unique pairs for 6: " + uniqueValuePairs(nums, 6)); }}Unique pairs for 6: [(1, 5), (2, 4)]
What this code does
- Even though
1and2and4appear twice in[1, 1, 2, 2, 3, 4, 4, 5], the duplicate-skipping loops ensure(1, 5)and(2, 4)are each added only once. - Note that the single
3at index4is never paired with itself because the loop requiresleft < right.
Example 5 · Counting all index pairs (i < j) that sum to target with duplicates
public class CountAllIndexPairsDemo { public static long countIndexPairs(int[] nums, int target) { long count = 0; int left = 0, right = nums.length - 1; while (left < right) { long sum = (long) nums[left] + nums[right]; if (sum < target) { left++; } else if (sum > target) { right--; } else { if (nums[left] == nums[right]) { long m = right - left + 1; count += m * (m - 1) / 2; break; } int leftVal = nums[left], rightVal = nums[right]; long cL = 0, cR = 0; while (left <= right && nums[left] == leftVal) { cL++; left++; } while (right >= left && nums[right] == rightVal) { cR++; right--; } count += cL * cR; } } return count; }
public static void main(String[] args) { System.out.println("Pairs in [1,1,2,4,4,4,5] for 5: " + countIndexPairs(new int[]{1, 1, 2, 4, 4, 4, 5}, 5)); System.out.println("Pairs in [3,3,3,3] for 6: " + countIndexPairs(new int[]{3, 3, 3, 3}, 6)); }}Pairs in [1,1,2,4,4,4,5] for 5: 6 Pairs in [3,3,3,3] for 6: 6
What this code does
- In
[1, 1, 2, 4, 4, 4, 5]withtarget = 5, two1s pair with three4s to form 2 × 3 = 6 index pairs. - In
[3, 3, 3, 3]withtarget = 6,nums[left] == nums[right] == 3with m = 4 elements, giving (4 × 3)/2 = 6 index pairs in O(1) arithmetic.
- Distinct values only: skip duplicate
nums[left]andnums[right]after every match. - All index pairs with
nums[left] < nums[right]: multiply left-run length c_L by right-run length c_R. - All index pairs with
nums[left] == nums[right]: add (m(m - 1))/2 where m = right - left + 1 and stop.
- Unique value pairs: After recording
(nums[left], nums[right]), advance bothleft++andright--, and then skip over any duplicate values (while (left < right && nums[left] == nums[left - 1]) left++;andwhile (left < right && nums[right] == nums[right + 1]) right--;). - All index pairs
(i, j)withi < j: Ifnums[left] == nums[right], then all elements innums[left..right]are identical! If there are m = right - left + 1 identical copies, they form (m(m - 1))/2 index pairs, and we can break immediately. Otherwise, count how many duplicates equalnums[left](c_L) and how many equalnums[right](c_R), add c_L × c_R to the total, and advance past both runs.
Next step
Check your understanding
10 quick questions