Link: 167. Two Sum II - Input Array Is Sorted - Medium
Track: NeetCode150
Question
Restate the problem
- Given a sorted integer array
numbersand an integertarget - Find two numbers such that they add up to
target - Return their indices as 1-indexed:
[index1, index2]withindex1 < index2 - Requirement:
- exactly one solution
- cannot use the same element twice
Edge Case
- Minimum length is 2
- Negative and duplicates are allowed
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Two Pointers |
Method 1
Approach
- Use two pointers:
left = 0,right = len(numbers) - 1 - While
left < right:- Compute
total = numbers[left] + numbers[right] - If
total == target: return[left + 1, right + 1](convert to 1-indexed) - If
total < target: moveleftrightward to increase the sum - If
total > target: moverightleftward to decrease the sum
- Compute
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left = 0
right = len(numbers) - 1
while left <= right:
total = numbers[left] + numbers[right]
if total == target:
return [left + 1, right + 1]
elif total < target:
left += 1
else:
right -= 1Common Mistake
- Forgetting the output is 1-indexed (
+1)