Algo-Sim › Two Pointers

Two Sum II - Input Array Is Sorted

Medium · Two Pointers · step through it in Java, Python and C++ on your own input

In a sorted array, find the two numbers that add up to the target, using O(1) extra space.

Problem

You are given a 1-indexed array numbers sorted in non-decreasing order and a target. Exactly one pair of different positions holds values that add up to target; return those two positions as [index1, index2] with index1 < index2. Use only constant extra space.

Constraints

Edge cases to test

Follow-up questions

Why is moving the smaller pointer safe?
If the sum is too small, the left value can’t pair with anything to the left of right, so it can be dropped: each step discards one candidate for good.
Why not binary search for each complement?
That is O(n log n). Two pointers use the sorted order on both ends at once: O(n), O(1) space.

Solution

Java

public int[] twoSum(int[] numbers, int target) {
    int left = 0, right = numbers.length - 1;
    while (left < right) {
        int sum = numbers[left] + numbers[right];
        if (sum == target) {
            return new int[] { left + 1, right + 1 };
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return new int[] { -1, -1 };
}

Python

def two_sum(numbers, target):
    left, right = 0, len(numbers) - 1
    while left < right:
        total = numbers[left] + numbers[right]
        if total == target:
            return [left + 1, right + 1]
        elif total < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        int left = 0, right = int(numbers.size()) - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return vector<int>{left + 1, right + 1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return vector<int>{-1, -1};
    }
};

More Two Pointers problems