Practice · Hashing · 3 of 7

Two Sum

You are given a list of integers nums and an integer target. Exactly two different positions in nums hold numbers that add up to target.

Return those two positions (indices, counting from 0) as a list of two numbers, in either order. You may not use the same position twice, although two positions may hold equal numbers.

Example 1

Input
nums = [3, 9, 14, 5], target = 8
Output
[0, 3]
nums[0] + nums[3] is 3 + 5 = 8.

Example 2

Input
nums = [6, 2, 6], target = 12
Output
[0, 2]
Two positions can hold the same number.

Constraints

  • nums holds 2 to 10⁴ numbers.
  • Every number, and target, is between −10⁹ and 10⁹.
  • At least one pair adds up to target; if several do, any one of them is accepted.
Brush up firstHash Table visualiser