Pair With Target Sum

EasyHash Map≈ 15 min

You are given a list of integers nums and an integer target. At most one pair of numbers in the list adds up to target. Return their indices, in any order, or an empty list [] if no pair does.

A number cannot be paired with itself, but the same value can appear twice at different indices.

Examples

text
nums = [4, 9, 1, 6], target = 7    →  [2, 3]
nums = [5, 12, 3, 8], target = 20  →  [1, 3]
nums = [6, 6], target = 12         →  [0, 1]
nums = [3, 8, 1], target = 20      →  []

In the first example, 1 + 6 = 7, and they sit at indices 2 and 3.

Constraints

  • The list holds between 2 and 10,000 numbers.
  • At most one pair adds up to target; when none does, the answer is [].
  • Aim for a solution that looks at each number once: O(n).
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.