Inward walk on a sorted array
The array is sorted. A too-small sum means advance lo; a too-big sum means retreat hi. Return 1-based indices.
Each comparison throws away an index forever, so the walk is linear. The problem asks for 1-based indices — add one at the end.
Algorithm
lo = 0,hi = n−1.- Equal → return
[lo+1, hi+1]. Too small →lo++. Too big →hi--.
- Time
- O(n)
- Space
- O(1)
class Solution: def twoSum(self, numbers: list[int], target: int) -> list[int]: lo, hi = 0, len(numbers) - 1 while lo < hi: s = numbers[lo] + numbers[hi] if s == target: return [lo + 1, hi + 1] if s < target: lo += 1 else: hi -= 1 return []