Skip to content
Problem 1 · LeetCode 1(opens in a new tab)

Two Sum

EasyArrays

You are given a list of whole numbers, nums, and a number called target. Exactly two numbers in the list add up to target.

Return the positions (indices) of those two numbers. You cannot use the same position twice, but two different positions may hold the same value. The two indices can be returned in any order.

Example 1

Input:  nums = [4, 9, 2, 13], target = 11
Output: [1, 2]
Why:    9 + 2 = 11
2 more examples and the constraints

Example 2

Input:  nums = [5, 1, 5], target = 10
Output: [0, 2]
Why:    the two 5s are at different positions

Example 3

Input:  nums = [-3, 8, 7], target = 4
Output: [0, 2]
Why:    -3 + 7 = 4

Constraints

  • 2 ≤ length of nums ≤ 10,000
  • Every number, and the target, is between −1,000,000,000 and 1,000,000,000
  • Exactly one pair adds up to the target

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Brute forceO(n²)
  2. Sort + two pointersO(n log n)
  3. Hash map, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 numbersVerdict
Brute forceO(n²)
Mention it, then move on
Sort + two pointersO(n log n)
Passes; costs a sort
Hash map, one passO(n)
Best; one pass, done

n = how many numbers are in the list.

Edge cases to test

  • Same value twice. [5, 1, 5] with target 10 must give [0, 2], never [0, 0].
  • Negative numbers. [-3, 8, 7] with target 4: the partner of −3 is 7.
  • Pair at the very end. The partner may be the last number you read.
  • Only two numbers. [1, 2] with target 3 is the whole list.

Common mistakes

  • Storing the number before checking for its partner, so 5 + 5 pairs index 0 with itself.
  • Returning the two values instead of their indices.
  • Sorting the list in place and losing the original indices.

How to talk through it

  1. 1Clarify. Can values repeat? Is there always exactly one answer? Does the order of the two indices matter?
  2. 2Give the brute force. Check every pair; say it is O(n²) and why that is too slow for 10,000 numbers.
  3. 3Name what you are searching for. For each x you look for target − x. A hash map makes that search O(1).
  4. 4Code the one pass. Check for the partner first, then store the number. Say why that order matters.
  5. 5Test out loud. Run the repeated-value and negative-number cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?