Back to Practice
#0032
Two Sum Indices
EasyDSA15 min10 XP
Problem
Given nums and target, return two indices whose values add to target. You may assume exactly one solution and cannot use the same element twice.
Why This Matters
Two Sum is the classic example of replacing a nested loop with a hash map of values already seen.
Function Signature
def two_sum(nums, target):
Examples
Example 1
Inputnums = [2, 7, 11, 15], target = 9
Output[0, 1]
nums[0] + nums[1] is 2 + 7 = 9.
Constraints
- Exactly one valid answer exists.
- Return indices, not values.
- Do not use the same index twice.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Classic pair
Input[2, 7, 11, 15], 9
Expected[0, 1]
The complement of 7 is 2, which was seen earlier.
Duplicate values
Input[3, 3], 6
Expected[0, 1]
The same value can appear twice, but the same index cannot be reused.
Hidden Test Categories
Negative numbersPair appears lateTarget is zeroLarge input