An efficient solution uses the two-pointer technique, which takes advantage of the fact that the array is already sorted.
Initialize Pointers: Start with two pointers. left points to the beginning of the array (index 0), and right points to the end.
left, right = 0, len(numbers) - 1Loop and Check Sum: Loop as long as the left pointer is less than the right pointer. In each iteration, calculate the sum of the values at the left and right pointers.
while left < right:
current_sum = numbers[left] + numbers[right]Adjust Pointers Based on Sum:
current_sum is greater than the target, it means you need a smaller sum. Since the array is sorted, you can achieve this by moving the right pointer one step to the left.current_sum is less than the target, you need a larger sum. Move the left pointer one step to the right.current_sum equals the target, you have found the solution.if current_sum > target:
right -= 1
elif current_sum < target:
left += 1
else:
# Solution found, return indicesReturn Result: Once the sum matches the target, return the indices of the two numbers. Since the problem asks for 1-based indexing, add 1 to both left and right before returning.
return [left + 1, right + 1]This two-pointer algorithm is much more efficient, with a time complexity of O(n) and a space complexity of O(1) as it only requires a single pass through the array.
class Solution:
def twoSum(self, numbers: list[int], target: int) -> list[int]:
left, right = 0, len(numbers) - 1
while left < right:
current_sum = numbers[left] + numbers[right]
if current_sum > target:
right -= 1
elif current_sum < target:
left += 1
else:
return [left + 1, right + 1]