Intuition
The given Python code implements a two-pointer approach to find two numbers in a sorted array that add up to a specific target.The idea behind this approach is to maintain two pointers, left and right, initially pointing to the beginning and end of the array, respectively. Since the array is sorted in non-decreasing order, moving the pointers inward allows you to explore possible pairs efficiently.Also this problem can be solved by using hash map.
Approach
If the sum of the numbers at the left and right pointers is equal to the target, you have found the pair.
If the sum is greater than the target, move the right pointer to the left to decrease the sum.
If the sum is less than the target, move the left pointer to the right to increase the sum.
Repeat steps 1-3 until you find the pair.
Complexity
- Time complexity:
The time complexity of this solution is O(n), where n is the length of the input array. In the worst case, you might need to traverse the entire array once to find the pair
- Space complexity:
The space complexity is O(1), constant extra space. This is because the solution only uses a fixed number of pointers (left and right) and does not rely on additional data structures that scale with the size of the input
Code
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left,right=0,len(numbers)-1
while(numbers[left]+numbers[right]!=target):
if numbers[left]+numbers[right]>target:
right-=1
elif numbers[left]+numbers[right]<target:
left+=1
return [left+1,right+1]