# 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; }```
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>
```
• Mustafa Magdy

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]

• 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