Two Sum II – Input array is sorted (Java)

This problem is similar to Two Sum.

To solve this problem, we can use two pointers to scan the array from both sides. See Java solution below:

public int[] twoSum(int[] numbers, int target) {
	if (numbers == null || numbers.length == 0)
		return null;
 
	int i = 0;
	int j = numbers.length - 1;
 
	while (i < j) {
		int x = numbers[i] + numbers[j];
		if (x < target) {
			++i;
		} else if (x > target) {
			j--;
		} else {
			return new int[] { i + 1, j + 1 };
		}
	}
 
	return null;
}

6 thoughts on “Two Sum II – Input array is sorted (Java)”

  1. This will not return correct answer, for example [2, 3, 4, 6, 7, 8] and target is 9
    what will achieve this is [1,5] but the correct answer is [2,4] because it will sum up to 9 before [1,5]

  2. actually in the problem 1, it mentioned that “Please note that your returned
    answers (both index1 and index2) are not zero-based.”, this is the two sun follow up problem, so I think that why they +1 here.

Leave a Comment