Two Sum

Easy Arrays & Hashing AI round

nums is a list of whole numbers, and target is a whole number.

Exactly one pair of different positions in nums holds numbers that add up to target.

Return the two positions of that pair, counting from 0, in either order.

Example 1

Input: nums = [14,-3,8,21,5], target = 35
Output: [0,3]

14 and 21 add up to 35, and they sit at positions 0 and 3. No other two numbers reach 35.

Example 2

Input: nums = [5,12,3,9], target = 15
Output: [1,2]

Example 3

Input: nums = [9,9,2], target = 18
Output: [0,1]

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • -10⁹ ≤ target ≤ 10⁹
  • Exactly one pair of different positions holds numbers that add up to target

Watch the explanation

More Arrays & Hashing

All Arrays & Hashing problems