167. Two Sum II - Input Array Is Sorted

167. Two Sum II - Input Array Is Sorted

Leetcode Blind 75

19th June 2022 ~ Dion Pinto

Description

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 less than equal index1 less than index2 less than equal numbers.length. (Problem)

Code (Python) -> 2 pointer


				
    class Solution:
        def twoSum(self, numbers: List[int], target: int) -> List[int]:
            l,r=0,len(numbers)-1
            while(l<r):
                s=numbers[l]+numbers[r]
                if(s==target):
                    return [l+1,r+1]
                elif(s>target):
                    r-=1
                elif(s<target):
                    l+=1
							
			

Time Complexity => o(n)

Space Complexity => o(1)

Back