You get a list of whole numbers, numbers, sorted from smallest to largest (equal values may sit next to each other), and a number target. Exactly one pair of different positions holds two values whose sum is target.
Return the positions of that pair as [index1, index2], counting from 1, with index1 < index2. Use only a constant amount of extra memory.
Example 1
Input: numbers = [2, 4, 7, 11, 15], target = 18 Output: [3, 4] Why: 7 + 11 = 18, at positions 3 and 4 (1-based)
2 more examples and the constraints
Example 2
Input: numbers = [-5, -2, 1, 3], target = -1 Output: [2, 3] Why: -2 + 1 = -1
Example 3
Input: numbers = [3, 3, 8], target = 6 Output: [1, 2] Why: two equal values at different positions
Constraints
- 2 ≤ length of numbers ≤ 30,000
- Every number, and the target, is between −1,000 and 1,000
numbersnever goes down from one position to the next- Exactly one pair adds up to the target
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- Binary search for the partnerO(n log n)
- Two pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 numbers | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| Binary search for the partner | O(n log n) | Passes; one search per number | |
| Two pointers | O(n) | Best; one pass, no memory |
n = how many numbers are in the list.
Edge cases to test
- Equal values. [3, 3, 8] with target 6 gives [1, 2]: two positions, one value.
- Only two numbers. [-1000, 1000] with target 0 is the whole list: [1, 2].
- Negative target. [-5, -2, 1, 3] with target -1: the rules for moving the pointers do not change.
- Pair at the two ends. The very first check can already be the answer.
Common mistakes
- Returning 0-based positions. The answer counts from 1.
- Using a hash map. It works, but breaks the constant-memory rule the sorted order is there to help with.
- Looping while lo <= hi, which can pair a number with itself.
How to talk through it
- 1Clarify. Are positions 1-based? Can values repeat? Is there always exactly one answer?
- 2Give the brute force. Every pair is O(n²); say it ignores the sorted order.
- 3Use the order. Binary search for target − x gets O(n log n). Then point out the two-pointer walk does better.
- 4Code the two pointers. Explain why a too-small sum means the left number can never work.
- 5Test out loud. Run the equal-values and two-number cases, and check the answer is 1-based.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?