Two Sum

EasyHash Maps and Sets

You are given an array of integers nums and an integer target. Find two different positions i and j such that nums[i] + nums[j] === target, and return them as an array [i, j].

The array is not sorted. Every input has exactly one valid pair. A position can't be used twice, although two different positions may hold equal values. You may return the two indices in either order.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9 and -10^9 <= target <= 10^9
  • Exactly one valid answer exists.
  • Aim for better than O(n²) time.

Examples

Example 1

Input: nums = [4,9,1,6], target = 7
Output: [2,3]

nums[2] + nums[3] = 1 + 6 = 7. Returning [3, 2] is accepted too.

Example 2

Input: nums = [3,1,5,7], target = 6
Output: [1,2]

1 + 5 = 6. Using the 3 at index 0 twice would also make 6, but a position can't be used twice.

Example 3

Input: nums = [6,6], target = 12
Output: [0,1]

Two different positions may hold the same value.

JavaScript you'll use: Map and Set

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
function twoSum(nums, target) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.