Two Sum

25 min · twoSum()

You're given an array of integers nums and a single integer target.

Exactly one pair of positions in the array adds up to target. Your job is to find that pair and return the two indices, in any order.

A few ground rules:

  • Each position can be used only once — a value can't pair with itself at the same index (though two different positions may hold equal values).
  • Exactly one valid answer exists for every input we'll hand you.

Constraints

  • 2 <= nums.length <= 10_000
  • -1_000_000_000 <= nums[i], target <= 1_000_000_000
  • Exactly one solution exists.

Hints

Start honest

What's the most obvious thing that could possibly work? Check every pair. Count how many pair-checks that is for 10,000 numbers before you fall in love with it.

What are you re-discovering?

While scanning, you keep asking: "have I already seen the number that would complete this one?" That question — have I seen X — is exactly what a hash map answers in O(1).

One pass is enough

For each nums[i], look up target - nums[i] in the map first, then store nums[i] → i. Storing after looking up is what prevents pairing an element with itself.

Follow-up

Could you do it in one pass even if the array were streaming in and you never saw it again?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  7,
  11,
  15
]
target = 9
Expected
[
  0,
  1
]
Why
2 + 7 = 9

Example 2

ready
Input
nums = [
  3,
  2,
  4
]
target = 6
Expected
[
  1,
  2
]
Why
2 + 4 = 6 (3 can't pair with itself)

Example 3

ready
Input
nums = [
  3,
  3
]
target = 6
Expected
[
  0,
  1
]
Why
two different positions may hold equal values

Interview signal

Asked at

GoogleAmazonAppleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite