Signature
def two_sum(nums, target):
Test Code
import random
_rng = random.Random(123456)
def _verify(nums, target):
result = two_sum(nums, target)
assert isinstance(result, (list, tuple)), f"Expected list/tuple, got {type(result)}"
assert len(result) == 2, f"Expected 2 elements, got {len(result)}"
i, j = result
assert isinstance(i, int) and isinstance(j, int), f"Indices must be ints"
assert 0 <= i < len(nums), f"First index {i} out of bounds"
assert 0 <= j < len(nums), f"Second index {j} out of bounds"
assert i != j, f"Indices must differ"
assert nums[i] + nums[j] == target, f"nums[{i}]={nums[i]} + nums[{j}]={nums[j]} != {target}"
# ── Basic edge cases ────────────────────────────────────────────────
_verify([1, 2, 3], 5) # simple consecutive
_verify([0, 0], 0) # zeros
_verify([-1, -2, -3], -3) # negatives
_verify([5, 1, 2, 3], 4) # non-consecutive, starts at index 1
def _generate_case(min_gap=1, avoid_ends=False):
"""Generate a random case where the valid pair satisfies constraints."""
for _attempt in range(500):
n = _rng.randint(5, 18)
lo = 1 if avoid_ends else 0
hi = n - 2 if avoid_ends else n - 1
if lo >= hi:
continue
i = _rng.randint(lo, max(lo, hi - min_gap))
j = i + _rng.randint(min_gap, hi - i)
if j > hi or i == j:
continue
nums = [_rng.randint(-500, 500) for _ in range(n)]
target = nums[i] + nums[j]
# Reject if another pair also sums to target (unique solution guarantee)
collision = False
for a in range(n):
for b in range(a + 1, n):
if (a == i and b == j):
continue
if nums[a] + nums[b] == target:
collision = True
break
if collision:
break
if collision:
continue
return nums, target
raise RuntimeError("Could not generate test case")
# Random cases that break consecutive-only and first-element heuristics
for _ in range(15):
nums, target = _generate_case(min_gap=2, avoid_ends=True)
_verify(nums, target)
Description
Return the indices of the two numbers that add up to the target. Example: Input: nums = [2, 7, 11, 15], target = 9 Output: [0, 1] Explanation: nums[0] + nums[1] == 9, so we return [0, 1]. You may assume that each input has exactly one valid pair of indices, and you may not use the same index twice.
Submit a Solution
Fastest Solutions
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
def two_sum(nums, target):
"""
Return the indices of the two numbers in `nums` that add up to `target`.
The function assumes that exactly one such pair exists and that the same
element cannot be used twice. It runs in O(n) time using a hash map.
"""
# Map from number value to its index (the first occurrence we have seen)
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
# Found the pair: return the earlier index and the current one
return [seen[complement], i]
# Store the current number only if we haven't seen it before.
# This preserves the first occurrence, which is enough because the
# problem guarantees a unique solution.
if num not in seen:
seen[num] = i
# If the input respects the problem constraints, we should never reach here.
raise ValueError("No two sum solution found")
def two_sum(nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
New Solutions
def two_sum(nums, target):
"""
Return the indices of the two numbers in `nums` that add up to `target`.
The function assumes that exactly one such pair exists and that the same
element cannot be used twice. It runs in O(n) time using a hash map.
"""
# Map from number value to its index (the first occurrence we have seen)
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
# Found the pair: return the earlier index and the current one
return [seen[complement], i]
# Store the current number only if we haven't seen it before.
# This preserves the first occurrence, which is enough because the
# problem guarantees a unique solution.
if num not in seen:
seen[num] = i
# If the input respects the problem constraints, we should never reach here.
raise ValueError("No two sum solution found")
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
def two_sum(nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]