PracticeNeetCode ↗LeetCode ↗
Given a 1-indexed array of integers numbers already sorted in non-decreasing order, find two numbers that add up to target and return their indices (1-indexed) as an array of two integers.
left = 0, right = len(numbers) - 1.left < right: compute total = numbers[left] + numbers[right].total == target, return [left + 1, right + 1] (converted to 1-indexed).total < target, move left forward; if total > target, move right backward.Time: O(n) — Space: O(1)
def twoSum(numbers: list[int], target: int) -> list[int]:
left, right = 0, len(numbers) - 1
while left < right:
total = numbers[left] + numbers[right]
if total == target:
return [left + 1, right + 1]
if total < target:
left += 1
else:
right -= 1
return []How the solution above works, piece by piece.
left = 0) and largest (right = n − 1) numbers.total == target: found. The problem uses 1-based indices, hence left + 1, right + 1.total < target: the sum must grow. Only moving left right can do that, because the array is sorted.total > target: the sum must shrink, so move right left. No pair is ever skipped that could have worked.Running it on numbers = [2, 7, 11, 15], target = 9:
right walks left until 2 + 7 hits 9 exactly.