2
5
8
11
15
19
[0][1][2][3][4][5]
Brute force
▸1given sorted arr, target2for i ← 0 to n − 2:3 fix arr[i]4 for j ← i + 1 to n − 1:5 if arr[i] + arr[j] == target → return (i + 1, j + 1)6return none
state
- target19
warming up the animation
Given a 1-indexed array of integers sorted in non-decreasing order, return the 1-based indices of the two numbers that add up to a given target — so the first element is index 1, not 0. Exactly one solution exists, and you may not use the same element twice.
▸1given sorted arr, target2for i ← 0 to n − 2:3 fix arr[i]4 for j ← i + 1 to n − 1:5 if arr[i] + arr[j] == target → return (i + 1, j + 1)6return none
line 1We want two positions (i, j) such that arr[i] + arr[j] = 19. We scan with 0-based positions and add 1 at the end, because the answer is 1-indexed.