Command Palette

Search for a command to run...

Problem 6.1 · Two PointersMedium

Two Sum II: Sorted Input

What it teaches: On sorted input, two pointers find a pair in O(n) time with O(1) space, beating the hash map's O(n) space.

Practise it on judges as “Two Sum II - Input Array Is Sorted”.

The problem

numbers is sorted in non-decreasing order. Find two numbers that add up to target and return their 1-based indexes [index1, index2] with index1 < index2. Exactly one solution exists. Use only O(1) extra space.

Example 1

Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]

Example 2

Input: numbers = [2, 3, 4], target = 6
Output: [1, 3]

Example 3

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

Constraints

  • 2 ≤ numbers.length ≤ 3 × 10⁴
  • Sorted non-decreasing
  • O(1) extra space

Pattern clues in the wording

  • → Sorted array + pair with a target sum
  • → O(1) extra space rules out the hash map

These clues point to Two Pointers: Opposite Ends: Start one pointer at each end and move them towards each other, using a rule to decide which one moves.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int L = 0, R = numbers.length - 1;
        return new int[0];
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
numbers = [2,7,11,15]
target = 9
[1,2]
2
numbers = [2,3,4]
target = 6
[1,3]
3
numbers = [-1,0]
target = -1
[1,2]

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: opposite-end pointers

Time O(n) Space O(1)

L = 0, R = n − 1. If the sum is below target, L++; above, R--; equal, return [L + 1, R + 1].

▶ Dry run: Closing in on 9numbers = [2, 7, 11, 15], target = 9
2
0
↑L
7
1
11
2
15
3
↑R

Step 1/32 + 15 = 17 > 9: drop 15.

Approach 1
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int L = 0, R = numbers.length - 1;
        while (L < R) {
            int sum = numbers[L] + numbers[R];
            if (sum == target) return new int[]{L + 1, R + 1};
            if (sum < target) L++;
            else R--;
        }
        return new int[0];
    }
}

Verdict: Uses the sorted order; no extra memory.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Negative numbers
  • Duplicates (e.g. [1, 1, 3], target 2)
  • Answer is the first and last element

Mistakes people make

  • Returning 0-based indexes.
  • Using a HashMap (works, but breaks the O(1) space rule).

Interview

Follow-up questions

Could binary search do it?