A-011● Day 112026.05.13mediumleetcode #167neetcode150
Two Sum II - Input Array Is Sorted
#array#two-pointers#binary-search
01
Problem
· problemGiven a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers index1 and index2, each incremented by one, as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space.
constraints
- · 2 ≤ numbers.length ≤ 3 × 10⁴
- · -1000 ≤ numbers[i] ≤ 1000
- · Array is sorted in non-decreasing order
- · -1000 ≤ target ≤ 1000
- · Exactly one solution exists
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐Should the returned indices be 0-based or 1-based?
- ☐Can we use the same array element twice?
- ☐Why does the sorted property matter for the solution?
- ☐What if the constant space constraint didn't exist?
- ☐Can the array contain negative numbers?
- ☐Could there be multiple valid solutions?
- ☐Should we return the actual numbers instead of indices?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize Pointers
○
l, r = 0, len(numbers) - 1
○
l, r = 0, len(numbers)
○
l, r = 1, len(numbers) - 1
step 2· Loop Condition
○
while l < r:
○
while l <= r:
○
while l < r - 1:
step 3· Calculate Current Sum│ nested
○
curSum = numbers[l] + numbers[r]
○
curSum = numbers[r] - numbers[l]
○
curSum = numbers[l + 1] + numbers[r]
step 4· If Sum Too Large, Move Right Pointer Left│ nested
○
r -= 1
○
l += 1
○
r -= 2
step 5· If Sum Too Small, Move Left Pointer Right│ nested
○
l += 1
○
r -= 1
○
l = l + 2
step 6· Found Exact Sum - Return 1-Indexed Indices│ nested
○
return [l + 1, r + 1]
○
return [l, r]
○
return [numbers[l], numbers[r]]
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[2,7,11,15] 9→
[1,2]
case 2
[2,3,4] 6→
[1,3]
case 3
[-1,0] -1→
[1,2]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.