DSA two pointers learning path Level 1 This level · 1 of 5
Medium dsa two-pointers

Two Sum II - Input Array Is Sorted

The 30 second answer

The array is already sorted, so I put one pointer at each end. If the sum is too small I move the left pointer up, and if it is too large I move the right pointer down. I return the 1-based indices when the sum matches the target. That is linear time and constant extra space.

Could you say this in an interview?

Problem Given a 1-indexed array of integers that is already sorted in non-decreasing order, find the two numbers that add up to a given target. Return their 1-based indices. The problem guarantees exactly one solution, and you may not use the same element twice. Original: LeetCode 167: Two Sum II - Input Array Is Sorted.

Understanding the prompt "1-indexed" means the answer is not the 0-based positions you use in the loop. "Already sorted" is the hint that two pointers beat a hash map. You still cannot use one element twice, but two equal values at different indices are fine.

Pattern recognition A sorted array plus a pair that sums to a target is the opposite-ends two-pointer pattern. You move the pointer that cannot improve the current sum.

Brute force Check every pair: O(n²) time. A hash map of value to index is O(n) time, but it uses O(n) space and ignores the sort.

Optimal Put lo at the start and hi at the end. If numbers[lo] + numbers[hi] equals the target, return lo + 1 and hi + 1. A sum that is too small must increase lo; a sum that is too large must decrease hi.

Alternatives For each index i, binary-search for target - numbers[i] to its right: O(n log n). That is a reasonable fallback if you are asked not to use two pointers, but it is slower.

Java solution

import java.util.Arrays;

public class TwoSumII {
    static int[] twoSum(int[] numbers, int target) {
        int lo = 0, hi = numbers.length - 1;
        while (lo < hi) {
            int sum = numbers[lo] + numbers[hi];
            if (sum == target) return new int[] {lo + 1, hi + 1}; // 1-indexed
            if (sum < target) lo++;
            else hi--;
        }
        return new int[0];
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9))); // [1, 2]
        System.out.println(Arrays.toString(twoSum(new int[] {2, 3, 4}, 6)));      // [1, 3]
        System.out.println(Arrays.toString(twoSum(new int[] {-1, 0}, -1)));       // [1, 2]
    }
}

Complexity O(n) time, O(1) extra space.

Edge cases

  • Negative numbers, as in [-1, 0] with target -1.
  • The two answers next to each other, or the first and last elements.

Follow-ups

  • The unsorted version is Two Sum, which needs a hash map.
  • Return all pairs, or extend the same idea to 3Sum.

Tests [2,7,11,15] with target 9 returns [1,2]. [2,3,4] with target 6 returns [1,3]. [-1,0] with target -1 returns [1,2].

How to say it in the interview "The array is sorted, so I start at both ends. A sum that is too small means I advance the left pointer; too large, I move the right. I add one to the indices because the answer is 1-based. Linear time, constant space."

Sources (1)
  1. LeetCode 167: Two Sum II - Input Array Is Sortedleetcode.com
Previous
Next