Leet Code

#8 167. Two Sum II - Input Array Is Sorted

brian | Published: Jan. 24, 2025, 5:29 p.m. | Updated: July 9, 2025, 11:43 p.m.

Profile Picture
'''
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, 
find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] 
and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer 
array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. 
You may not use the same element twice.

Your solution must use only constant extra space.
'''


class Solution(object):
    def twoSum(self, nums:list[int], target:int):
       
        leftPointer = 0
        rightPointer = len(nums) - 1

        # we dont want to cross paths because we cant use the same indices
        while leftPointer < rightPointer:
            answer = nums[leftPointer] + nums[rightPointer]
            #if the answer is greater than the target, then mode the right pointer to the left to make it smaller
            if answer > target:
                rightPointer-=1
            #if the answer is less than the target, move the left pointer to make it bigger
            elif answer < target:
                leftPointer+=1
            else:
                return leftPointer+1, rightPointer+1
            

nums = [1, 2, 3, 4, 5]
target = 4
object = Solution()

print(object.twoSum(nums, target))