Pair with Given Sum in Sorted Array

Given an array sorted in non-decreasing order and a target sum, return the two values that add up to the target — or an empty array if no such pair exists.

MediumRecommendedTwo Pointers
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array sorted in non-decreasing order and a target sum, return the two values that add up to the target — or an empty array if no such pair exists.

Why solve this?

The direct sorted-array counterpart to Two Sum: instead of a hash map trading space for one-pass lookup, sortedness lets two converging pointers find the pair in-place with no extra memory.

Pattern Recognition

Whenever an array is sorted and you need two elements that hit an exact target sum, converging pointers from both ends let you decide which side to move using just one comparison — no hash set required.

Prerequisites

  • Two Sum — the same target-sum goal, but sortedness replaces the hash map.
  • Comfort with sorted-array two pointers.

Hints

  1. Start with one pointer at each end of the array — their sum is either too small, too big, or exactly right.
  2. If the current sum is too small, the only way to increase it is to move the left pointer inward (since the array is sorted).
  3. If the current sum is too big, move the right pointer inward instead.

Approach

This problem's return contract is the two matching values, not their indices — unlike Two Sum, sortedness makes values themselves unambiguous to work with and keeps the pointer logic focused on the sum comparison rather than index bookkeeping. Start a left pointer at index 0 and a right pointer at the last index. At each step, compare nums[left] + nums[right] to the target: if they're equal, that pair is the answer. If the sum is smaller than the target, the only way to increase it (since the array is sorted) is to move left forward. If the sum is larger, move right backward. If the pointers cross without ever matching, no pair exists, so return an empty array.

Code

Solution.java
class Solution {
    public int[] pairSum(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum == target) {
                return new int[] { nums[left], nums[right] };
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[0];
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays