Two numbers that add up to a target

Return the positions [i, j] (with i < j) of the two numbers in nums that add up to target. Every test has exactly one answer, and you may not use the same position twice.

Write two_sum(nums, target) in Python, twoSum(nums, target) in JavaScript or TypeScript, or void two_sum(int nums[], int n, int target, int result[]) in C. Level: Medium.

Examples

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
  • 2 ≤ length of nums ≤ 10,000
  • Positions start at 0
  • Bonus: one pass through the list instead of two nested loops

Hint

Walk the list once and remember each number's position in a dictionary / Map. For each x, check whether target − x was already seen.

The approach, step by step

  1. seen = empty map, i = 0
  2. i < length?
  3. need = target − nums[i]
  4. need in seen?
  5. Return [seen[need], i]
  6. seen[nums[i]] = i, i = i + 1

← All practice problems

Try AI Flowchart free →