Two Sum II – Input array is sorted (Java)

This problem is similar to Two Sum.

To solve this problem, we can use two points 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;
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Young Zhang

    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.

  • Rathna

    How binary search works for 2 sum?

  • Shru

    Yes. It should be return new int[]{i,j};

  • Prakash Devta

    Shouldn’t it return

    return new int[] { i, j };

  • Renzo

    This code is O(n). It can be O(log(n)). The code in Python: https://github.com/renzon/code_interview_training/blob/master/two_sum.py