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>

  1. Renzo on 2016-2-5

    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

  2. Prakash Devta on 2017-1-4

    Shouldn’t it return

    return new int[] { i, j };

  3. Shru on 2017-2-10

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

  4. Rathna on 2017-2-13

    How binary search works for 2 sum?

  5. Young Zhang on 2017-3-19

    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

*