interviewmind

Two Sum

Two Sum is an easy coding interview question. You’re given an array of integers nums and an integer target. Return the indices of the two numbers in nums that add up to target. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.

Updated · By InterviewMind

Practice this question

Free in your browser, no account.

The problem

Coding · Easy

You’re given an array of integers nums and an integer target. Return the indices of the two numbers in nums that add up to target.

Every input has exactly one answer, and the same element can’t be used twice. Return the two indices in either order.

Example 1

Inputnums = [2,7,11,15], target = 9Output[0,1]

nums[0] + nums[1] = 2 + 7 = 9.

Example 2

Inputnums = [3,2,4], target = 6Output[1,2]

The 3 can’t pair with itself, so the answer is 2 + 4.

Example 3

Inputnums = [3,3], target = 6Output[0,1]

Constraints

  • 2 ≤ nums.length ≤ 10⁴
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • -10⁹ ≤ target ≤ 10⁹
  • Exactly one answer exists

Hints

Open one at a time, and try the question again after each.

Hint 1

For each number, you already know the partner it needs: target minus that number. The only question is whether you’ve passed it yet.

Hint 2

Keep a hash map from each value you’ve seen to its index. Then a single pass is enough, with one lookup per number.

Hint 3

Look up the partner before you store the current number, so a value never pairs with itself, and duplicates like [3, 3] still work.

Practice it out loud

In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.

Practice this question

More coding questions

interviewmind

Clarity under pressure.

Download for macOSWindows

On an Intel Mac? Download for Intel