150NeetCode 150

11.Two Sum II

MediumTwo Pointers ยท 2/5

Problem

You are given a 1-indexed array numbers sorted in non-decreasing order and an integer target. Find two numbers that add up to target and return their indices as [index1, index2] with 1 <= index1 < index2.

Exactly one solution exists, you may not use the same element twice, and your solution must use only constant extra space.

Examples

Input:  numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]
Explanation: 2 + 7 = 9, at 1-indexed positions 1 and 2.
Input:  numbers = [2, 3, 4], target = 6
Output: [1, 3]
Explanation: 2 + 4 = 6.
Input:  numbers = [-1, 0], target = -1
Output: [1, 2]

Constraints

  • 2 <= numbers.length <= 3 * 10^4
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order.
  • -1000 <= target <= 1000
  • Exactly one solution exists.

๐Ÿ’ก Key Insight

Sortedness gives direction. With pointers at the smallest (left) and largest (right) values, if numbers[left] + numbers[right] is too small, the only way to increase it is left++; if too large, right--. Each move permanently eliminates one element that cannot be part of the answer, so one O(n) sweep with O(1) space finds the pair.

Brute Force

TimeO(nยฒ)SpaceO(1).

Intuition

Check every pair (i, j) with i < j. This ignores the sorted order entirely.

Algorithm

  1. For i = 0..n-1, for j = i+1..n-1:
  2. If numbers[i] + numbers[j] == target, return [i + 1, j + 1].

Visualization

numbers = [2, 3, 4], target = 6
i=0: 2+3=5 โœ—, 2+4=6 โœ“ โ†’ [1, 3]

Code

java
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int n = numbers.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (numbers[i] + numbers[j] == target) {
                    return new int[] {i + 1, j + 1}; // convert to 1-indexed
                }
            }
        }
        return new int[0];
    }
}

Complexity

  • Time: O(nยฒ) โ€” all pairs in the worst case.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force O(nยฒ) O(1)
Binary Search O(n log n) O(1)
Two Pointers O(n) O(1)

Common Pitfalls

  • Returning 0-indexed positions โ€” this problem is 1-indexed.
  • Using a HashMap like the original Two Sum โ€” it works but violates the constant-space requirement.
  • Moving the wrong pointer (e.g. left++ when the sum is already too large) โ€” that throws away an element that may be part of the answer.
  • In binary search, searching the whole array instead of i + 1 .. n - 1 can return the same index i when need == numbers[i].