Skip to lesson

Pair sum in a sorted array

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).

  1. Initialize left = 0 and right = nums.length - 1.
  2. Loop while (left < right) and compute sum = (long) nums[left] + nums[right].
  3. If sum == target, return the indices or values.
  4. If sum < target, increment left++; otherwise decrement right--.

Find two numbers that add up to 10

Step 1 of 6

Array: 1, 3, 4, 6, 8, 11. left at index 0. right at index 5.
target
10
Start with 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)

PairSumBrute.javaJava
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)));    }}
Output
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)

PairSumBinarySearch.javaJava
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)));    }}
Output
Target 9:  [0, 1]
Target 22: [1, 3]
Target 10: [-1, -1]

What this code does

  • For each nums[i], binary search looks for target - 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)

PairSumSortedDemo.javaJava
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)));    }}
Output
Target 9:  [0, 1]
Target 22: [1, 3]
Target 10: [-1, -1]

What this code does

  • For target = 22 on [2, 7, 11, 15]: first 2 + 15 = 17 < 22 (left moves to 1), then 7 + 15 = 22, returning [1, 3].
  • Casting nums[left] to long before addition prevents integer overflow when values are close to Integer.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. Since nums[right] is already the largest remaining value, nums[left] cannot possibly reach target with any element in left..right. We increment left++ to pick a larger left number.
  • If sum > target, the current sum is too large. Since nums[left] is already the smallest remaining value, nums[right] cannot possibly reach target with any element in left..right. We decrement right-- 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.

while (left < right) {
long sum = (long) nums[left] + nums[right];
if (sum == target) return new int[]{left, right};
if (sum < target) left++; else right--;
}

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*!

Each comparison eliminates an entire row (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)

UniquePairsDemo.javaJava
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));    }}
Output
Unique pairs for 6: [(1, 5), (2, 4)]

What this code does

  • Even though 1 and 2 and 4 appear 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 3 at index 4 is never paired with itself because the loop requires left < right.

Example 5 · Counting all index pairs (i < j) that sum to target with duplicates

CountAllIndexPairsDemo.javaJava
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));    }}
Output
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] with target = 5, two 1s pair with three 4s to form 2 × 3 = 6 index pairs.
  • In [3, 3, 3, 3] with target = 6, nums[left] == nums[right] == 3 with m = 4 elements, giving (4 × 3)/2 = 6 index pairs in O(1) arithmetic.
  • Distinct values only: skip duplicate nums[left] and nums[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.
  1. Unique value pairs: After recording (nums[left], nums[right]), advance both left++ and right--, and then skip over any duplicate values (while (left < right && nums[left] == nums[left - 1]) left++; and while (left < right && nums[right] == nums[right + 1]) right--;).
  2. All index pairs (i, j) with i < j: If nums[left] == nums[right], then all elements in nums[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 equal nums[left] (c_L) and how many equal nums[right] (c_R), add c_L × c_R to the total, and advance past both runs.

Next step

Check your understanding

10 quick questions