Skip to the solution
EasyDSA6 min read

Two Sum — Find indices of two numbers that add to target

875 views

The problem

Problem, as an interviewer would state it: "Implement twoSum(nums, target) — returning the INDICES of the two numbers in the array that add up to target, without using the same array element twice."

Examples:

Code
twoSum([2,7,11,15], 9); // [0,1] -- nums[0]+nums[1] = 2+7 = 9

Clarifying questions expected:

  • Does the answer need to return real ARRAY INDICES, or the actual matching VALUES themselves?
  • If the SAME value could theoretically pair with itself to reach the target, can a single array element be used TWICE?
  • Is exactly one valid answer guaranteed to exist, or does the function need to handle a genuinely "no valid pair" case?

Code / implementation expected: Yes — real, direct proof of correct index-pair detection, confirmation the same index is never used twice even with duplicate values present, and correct handling of a genuinely unsolvable case.

  • array
  • hash-map
  • two-sum

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: twoSum() correctly finds index pairs summing to target, confirming a single value is never matched against itself at the same index

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 27 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement an Immutable setIn(obj, path, value) That Never Mutates the Original

Continue