Problem description

You are handed a list of whole numbers called `nums` together with a single number named `target`. Your job is to find the one pair of positions in the list whose values add up exactly to `target`, and then hand back those two positions.

You can safely assume that precisely one such pair exists in the input, so there is never any ambiguity about the answer. Each position may only be used a single time, meaning you cannot pair a number with itself by reusing its index.

Example 1

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

The values at positions 0 and 1 are 2 and 7, and 2 + 7 equals the target 9.

Example 2

Input: nums = [3,2,4], target = 6

Output: [1,2]

Adding 2 (position 1) and 4 (position 2) gives 6, which matches the target.

Example 3

Input: nums = [3,3], target = 6

Output: [0,1]

Both entries are 3, and combining the two different positions produces the target 6.

Constraints

  • 2 ≤ nums.length ≤ 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • -10^9 ≤ target ≤ 10^9
  • Exactly one valid answer exists.

After the pattern

Now solve one you haven't seen.

Ledger Reconciliation is our own problem on the technique behind Two Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free