## 167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

b'
\n
\n\n
\n

## Solution

\n
\n

#### Approach #1 (Two Pointers) [Accepted]

\n

Algorithm

\n

We can apply Two Sum\'s solutions directly to get time, space using brute force and time, space using hash table. However, both existing solutions do not make use of the property where the input array is sorted. We can do better.

\n

We use two indexes, initially pointing to the first and last element respectively. Compare the sum of these two elements with target. If the sum is equal to target, we found the exactly only solution. If it is less than target, we increase the smaller index by one. If it is greater than target, we decrease the larger index by one. Move the indexes and repeat the comparison until the solution is found.

\n

Let be the input array that is sorted in ascending order and the element , be the exactly only solution. Because we are moving the smaller index from left to right, and the larger index from right to left, at some point one of the indexes must reach either one of or . Without loss of generality, suppose the smaller index reaches first. At this time, the sum of these two elements must be greater than target. Based on our algorithm, we will keep moving the larger index to its left until we reach the solution.

\n
`class Solution {\npublic:\n    vector<int> twoSum(vector<int>& numbers, int target) {\n        int low = 0, high = numbers.size() - 1;\n        while (low < high) {\n            int sum = numbers[low] + numbers[high];\n            if (sum == target)\n                return {low + 1, high + 1};\n            else if (sum < target)\n                ++low;\n            else\n                --high;\n        }\n        return {-1, -1};\n    }\n};\n`
\n

Do we need to consider if overflows? The answer is no. Even if adding two elements in the array may overflow, because there is exactly one solution, we will reach the solution first.

\n

Complexity analysis

\n
\n
• \n

Time complexity : .\nEach of the elements is visited at most once, thus the time complexity is .

\n
• \n
• \n

Space complexity : .\nWe only use two indexes, the space complexity is .

\n
• \n
\n

Analysis written by @maonag6.

\n
'