Link: 167. Two Sum II - Input Array Is Sorted - Medium
Track: NeetCode150

Question

Restate the problem

  • Given a sorted integer array numbers and an integer target
  • Find two numbers such that they add up to target
  • Return their indices as 1-indexed: [index1, index2] with index1 < index2
  • Requirement:
    • exactly one solution
    • cannot use the same element twice

Edge Case

  • Minimum length is 2
  • Negative and duplicates are allowed

MethodApproachTime ComplexitySpace 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: move left rightward to increase the sum
    • If total > target: move right leftward to decrease the sum

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 -= 1

Common Mistake

  • Forgetting the output is 1-indexed (+1)