#167
Medium
Two Pointers

Two Sum II

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

ArrayTwo Pointers

Pattern fit

Because the array is sorted, each comparison tells you exactly which side can move without losing the answer.

Key observation

If the current sum is too small, only the left pointer can help; if too large, only the right pointer can help.

Target complexity

O(n) / O(1)

How to break down the solution cleanly

1

Because the array is sorted, each comparison tells you exactly which side can move without losing the answer.

2

If the current sum is too small, only the left pointer can help; if too large, only the right pointer can help.

3

Write down what each pointer means before you move them.

4

Use the current comparison to prove which side can be safely discarded.

Reference implementation

Python
# Generic pattern template
# Opposite-direction pointers on a sorted array
left, right = 0, len(nums) - 1
while left < right:
    if good(nums[left], nums[right]):
        return answer
    if should_move_left(nums[left], nums[right]):
        left += 1
    else:
        right -= 1

# Fast/slow pointers
slow = 0
for fast in range(len(nums)):
    if keep(nums[fast]):
        nums[slow] = nums[fast]
        slow += 1

Common pitfalls

warning

Falling back to hash map and missing the sorted-order insight.

warning

Returning zero-based indices when the problem expects one-based.

Common follow-ups

Can you explain why the discarded half can never contain the answer?

How does this differ from unsorted Two Sum?

Continue with related problems

Build repeatable depth inside the Two Pointers cluster before moving on.

view_weekBack to the pattern page
LeetCode 167. Two Sum II Guide | Interview AiBox