167. Two Sum II — Input Array Is Sorted
At a Glance
- Topic: two-pointers
- Pattern: Two Pointers
- Difficulty: Medium
- Companies: Amazon, Google, Meta, Apple, Adobe
- Frequency: High
- LeetCode: 167
Problem (one-liner)
Given a 1-indexed sorted strictly increasing array numbers and target, return the 1-indexed pair [leftIndex, rightIndex] with leftIndex < rightIndex such that numbers[leftIndex] + numbers[rightIndex] == target. Exactly one solution exists.
Recognition Cues
- Sorted array + pair sum
- "Two pointers" classic
- 1-indexed output (LeetCode quirk)
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force —
O(n²)pairs. - Better — binary search for complement —
O(n log n). - Optimal —
O(n)time /O(1)space — inward pointers: too small → move left up; too large → move right down.
Optimal Solution
Go
func twoSum(numbers []int, target int) []int {
left, right := 0, len(numbers)-1
for left < right {
sum := numbers[left] + numbers[right]
if sum == target {
return []int{left + 1, right + 1}
}
if sum < target {
left++
} else {
right--
}
}
return nil
}JavaScript
function twoSum(numbers, target) {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
const sum = numbers[left] + numbers[right];
if (sum === target) {
return [left + 1, right + 1];
}
if (sum < target) {
left++;
} else {
right--;
}
}
return [];
}Walkthrough
Input: numbers = [2,7,11,15], target = 9
| left | right | sum | action |
|---|---|---|---|
| 0 | 3 | 17 | right-- |
| 0 | 2 | 13 | right-- |
| 0 | 1 | 9 | return [1,2] (1-indexed) |
Invariant: shrinking window preserves uniqueness of solution; monotonic sum guides pointer moves.
Edge Cases
- Adjacent answer pair
- Duplicates allowed in values (distinct indices still required)
Pitfalls
- Returning 0-based indices
- Using hash map unnecessarily when sorted two-pointer exists
Similar Problems
- 1. Two Sum — unsorted → hash map.
- 15. 3Sum — adds outer anchor.
- 11. Container With Most Water — different objective, same pointer motion grammar.
Variants
- Two sum ≤ target — last valid pair tracking.
- Two sum closest — track best absolute difference.
Mind-Map Tags
#two-pointers #sorted-array #pair-sum #one-indexed
Last updated on
Spotted something unclear or wrong on this page?