Skip to main content

Two Sum

Question

Given an array of integers, find the two numbers whose sum is equal to a given target number.

Example 1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]

Solution

all//Two Sum.py


def two_sum(nums, target):
seen = {}
for i, val in enumerate(nums):
diff = target - val
if diff in seen:
return [seen[diff], i]
seen[val] = i
return []