───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───

Problem

  • 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 𝑂(1) additional space.

Solution

  • This is a pretty obvious two pointer problem, mainly since we know the array is sorted
  • We can get a sum of the numbers at the left and right pointers
    • If the sum is same as the target, we return the indices [r + 1, l + 1]
    • If the sum is greater than the target, we decrement the right pointer
    • If the sum is less than the target, we increment the left pointer
class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
	    # time complexity: O(n)
	    # space complexity: O(1)
    
        l, r = 0, len(numbers) - 1
 
        while l < r:
            current = numbers[l] + numbers[r]
 
            if current == target:
                return [l + 1, r + 1]
            elif current > target:
                r -= 1
            elif current < target:
                l += 1

───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───