Skip to content

Two Sum

LeetCode

01 · Question

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

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

02 · Solution

Reference solution

1def twoSum(nums: List[int], target: int) -> List[int]:
2 seen = {}
3
4 for i, x in enumerate(nums):
5 need = target - x
6 if need in seen:
7 return [seen[need], i]
8 seen[x] = i
9
10 return []