Two Sum

LeetCode

LeetCode: https://leetcode.com/problems/two-sum/

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]
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 []
i
2
0
7
1
11
2
15
3
target=9
Step 1 / 2
Step 1:
Start with an empty map. i=0, x=2, need=7 (not found). Store 2->0.
Pointers: i=0
Focus: select @ [0]
target=9