Author
Result
0.1375 s
Code
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")