Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Two Sum II

LeetCode #167Medium
Sorted input · find indices that add up to target

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.

Asked atAmazonMicrosoftApple
step 1 / 32
2
5
8
11
15
19
[0][1][2][3][4][5]
Brute force
1given sorted arr, target
2for i ← 0 to n − 2:
3 fix arr[i]
4 for ji + 1 to n − 1:
5 if arr[i] + arr[j] == target → return (i + 1, j + 1)
6return none
state
  • target19

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.