Two Sum II

Find two numbers in a sorted array that add up to a target.

Pattern

Two Pointers Sorted

This problem follows the Two Pointers Sorted pattern, commonly found in the Two Pointers category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Left and right pointers. Move left up if sum too small, right down if too large.

Key Insight

Because the array is sorted, moving left increases the sum and moving right decreases it — this gives you O(n) instead of the O(n²) brute force.

Step-by-step

  1. 1Initialize left = 0, right = length - 1
  2. 2Calculate sum = numbers[left] + numbers[right]
  3. 3If sum equals target, return [left+1, right+1] (1-indexed)
  4. 4If sum < target, move left pointer right (need larger value)
  5. 5If sum > target, move right pointer left (need smaller value)
  6. 6Repeat until found — guaranteed exactly one solution

Pseudocode

left = 0, right = len(nums) - 1
while left < right:
    sum = nums[left] + nums[right]
    if sum == target:
        return [left + 1, right + 1]
    else if sum < target:
        left++
    else:
        right--
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Two Pointers Problems

Master this pattern with YeetCode

Practice Two Sum II and similar Two Pointers problems with flashcards. Build pattern recognition through active recall.

Practice this problem