~/leetcode $ 167. Two-Sum-II-Input-Array-Is-Sorted

Question Link

Difficulty: Medium

An extension to the classic two sum question but the input array is sorted and we want to use constant space (the solution to the original two sum used a hashset which requires O(n) space).

Here, we can use the fact that the input list is sorted in order to solve this problem in constant space. If we instantiate our left and right pointers on either side of the list (one pointer at the start and the other pointer at the end) and use the sum of the two numbers they are pointing to as our initial sum, we can do the following while the left pointer is still smaller than the right pointer:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int left = 0;
        int right = numbers.size() - 1;

        while (left < right) {
            int currSum = numbers[left] + numbers[right];
            if (currSum == target) {
                return {left + 1, right + 1};
            }

            if (currSum > target) {
                --right;
            } else {
                ++left;
            }
        }

        return {-1, -1};
    }
}

Time Complexity: O(n)

Space Complexity: O(1)

Time Taken: 3m 08s