Two Sum II - Input Array Is Sorted

Medium Arrays & Hashing Two Pointer Original on LeetCode

Two Sum II - Input Array Is Sorted is a medium arrays & hashing problem solved with the two pointer pattern. The best approach, optimal (two pointers), runs in O(n) time and O(1) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (binary search for the partner) up.

Problem

The array numbers is sorted in non-decreasing order. Find two numbers that add up to target and return their positions as a 1-indexed pair [index1, index2] with index1 < index2.

Use only constant extra space.

Examples

Example 1

Input
numbers = [1, 3, 4, 6, 9], target = 10
Output
[2, 5]
Why
numbers[1] + numbers[4] = 1 + 9 = 10, reported 1-indexed.

Example 2

Input
numbers = [-3, -1, 0], target = -1
Output
[2, 3]

Constraints

  • 2 <= numbers.length <= 3 * 10^4
  • numbers is sorted in non-decreasing order.
  • Exactly one solution exists. Use only constant extra space.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (binary search for the partner)O(n log n)O(1)
Optimal (two pointers)O(n)O(1)

1Brute force (binary search for the partner)

TimeO(n log n)
SpaceO(1)

For each index i, binary search the rest of the array for target - numbers[i].

  1. For each i, search numbers[i + 1..n - 1] for target - numbers[i].
  2. Return the 1-indexed pair when found.
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        for (int i = 0; i < numbers.length; i++) {
            int need = target - numbers[i];
            int lo = i + 1, hi = numbers.length - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                if (numbers[mid] == need) return new int[] { i + 1, mid + 1 };
                if (numbers[mid] < need) lo = mid + 1; else hi = mid - 1;
            }
        }
        return new int[0];
    }
}

2Optimal (two pointers)

TimeO(n)Each step moves one pointer inward, at most n steps.
SpaceO(1)

Start with the smallest and largest values. If their sum is too small, the left value is too small for any partner, so move left forward. If too big, move right back.

  1. lo = 0, hi = n - 1.
  2. sum < target: lo++. sum > target: hi--.
  3. On a match return [lo + 1, hi + 1].
class Solution {
    public 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 };
            if (sum < target) lo++; else hi--;
        }
        return new int[0];
    }
}

Edge cases to test

  • Negative numbers
  • Duplicates such as [2, 2] with target 4

Hints

Hint 1

If the sum of the two ends is too big, which end can never be part of the answer?

FAQ

What is the best time complexity for Two Sum II - Input Array Is Sorted?

Optimal (two pointers) runs in O(n) time and O(1) extra space. Each step moves one pointer inward, at most n steps.

Which pattern does Two Sum II - Input Array Is Sorted use?

It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Valid Triangle Number, Container With Most Water, Trapping Rain Water.

Is there a brute force solution for Two Sum II - Input Array Is Sorted?

Yes. Brute force (binary search for the partner) takes O(n log n) time and O(1) space. For each index i, binary search the rest of the array for target - numbers[i].

Which edge cases should I test for Two Sum II - Input Array Is Sorted?

Negative numbers; Duplicates such as [2, 2] with target 4.