Prompt:

Two Integer Sum II

MediumTopicsCompany TagsHints

Given an array of integers numbers that is sorted in non-decreasing order.

Return the indices (1-indexed) of two numbers, [index1, index2], such that they add up to a given target number target and index1 < index2. Note that index1 and index2 cannot be equal, therefore you may not use the same element twice.

There will always be exactly one valid solution.

Your solution must use O(1)O(1) additional space.

Example 1:

Input: numbers = [1,2,3,4], target = 3
 
Output: [1,2]

Explanation:
The sum of 1 and 2 is 3. Since we are assuming a 1-indexed array, index1 = 1, index2 = 2. We return [1, 2].

Solution:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) 
    {
        int right = numbers.size();
        int left = 0;
        
        while(left < right)
        {
            int sum = numbers[left] + numbers[right-1];
 
            if(sum == target)
            {
                vector<int> returnVec = {left+1, right};
                return returnVec;
            }
 
            if(numbers[left] + numbers[right-1] > target)
            {
                right--;
            }
            else
            {
                left++;
            }
        }
        vector<int> returnVec = {left, right};
        return returnVec;
    }
};
 

Explanation

This one is pretty cool, so basically it is two sum once again but the difference is that this time the given input is a sorted array, and one of the constraints is that we must actually use O(1) space, which means that the standard hashmap solution of indexing the difference would work here, but break that rule.

The cool thing is though, is that we can just use a two pointers solution which is O(n) still and has only the one time complexity. We understand that the integers on the end of the array are largest, and the ones on the left are smallest, so we can actually just add the two and if the number we get is bigger than the target, we know we need to move inward from the right towards the smaller numbers, or we need to move inward from the left to the larger numbers.

Then, if the two ever cross, we know that there is no more possible combinations of values so we end up with case a O(n/2) solution if the target does not exist in the array. This way we know which way the two pointers move, and we can find the target with no extra space complexity, the only issue of course being sorting which takes O(nlog(n)) time if the array is not already sorted.