Skip to main content

Warm-up hash map · arrays

Two receipts

Two receipts in the pile add up to the refund. Find them in one pass.

Write twoSum(nums, target): return the indices [i, j] of two different numbers in nums that add up to target, with i < j. If no pair exists, return [].

If more than one pair works, return the one with the smallest j, and for that j the smallest i. That is exactly what you get by walking left to right once and remembering the first index where you saw each value.

Call show(line) with a short string each step (what you are holding, what you need, what you have seen) and the stage prints your trail.

Example: twoSum([2, 7, 11, 15], 9) returns [0, 1].

Tests you can see

  • twoSum([2,7,11,15], 9)[0,1]
  • twoSum([3,2,4], 6)[1,2]
  • twoSum([-3,4,3,90], 0)[0,2]

More tests are hidden. The server runs them all before a time counts.

Call show() while your code works and the run plays back here.

javascripttwoSum()

Tab indents · Cmd/Ctrl+Enter runs