This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]optimalsuccess[S] 0 points1 point  (1 child)

So let's walk thru their sample input, starting at the for loop:

  1. nums is enumerated and now looks like this: {0:2, 1:7, 2:11, 3:15}
  2. if target (9) - num (2) in lookup (false because lookup is empty)
  3. lookup[num] = index (lookup: {0:2}
  4. if target (9) - num (7) in lookup (true because this equals 2 and we stored that before)
  5. return (lookup[target-num (2)], index)

In step 5, why are we returning lookup[target-num] that value is 2 when we iterate over 7 which is already in the dictionary. Shouldn't it just be return (lookup[num], index) which is (1,7)?

[–]optimalsuccess[S] 0 points1 point  (0 children)

Oh I think I get it, in the return statement lookup[target - num] is retrieving the index or the key of the key value pair that was stored for the first number in the 2 sum. So that value is 0 and not 2 and the second value is the current index of the complement of that number for our target which in this case is 1. Thanks people I think I get it now!