Problem statement

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

Solution

If array is already sorted, the best algorithm is to use two pointers approach.

Complexity

Time complexity is O(n) and space is O(1)

Code

class Solution:
    def twoSum(self, nums, target):
        beg, end = 0, len(nums) - 1
        while beg < end:
            cand = nums[beg] + nums[end]
            if cand > target:
                end -= 1
            elif cand < target:
                beg += 1
            else:
                return [beg + 1, end + 1]