Back to Practice
#0231
Two Sum Indexes
EasyDSA18 min10 XP
Problem
Given a list of integers and a target, return the two indexes whose values add to target. Return the smaller index first.
Why This Matters
Two Sum is the classic shift from nested-loop thinking to remembering useful past values.
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, which equals 9.
Constraints
- Return the exact requested value.
- Handle empty or small inputs when the prompt allows them.
- Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Front pair
Input[2, 7, 11, 15], target = 9
Expected[0, 1]
The first two values make the target.
Repeated values
Input[3, 3, 4], target = 6
Expected[0, 1]
The same value can be used from two different indexes.
Hidden Test Categories
negative numberspair appears lateno pair returns empty list