Amazon's Two Sum LeetCode Solution Explained - JavaScript [Step by step using hash table]

preview_player
Показать описание
The tutorial exaplains how this problem can be solved optimally using a hash map (aka hash table or dictionary), at O (n) time complexity & O (1) space complexity.
Рекомендации по теме
Комментарии
Автор

how did the key value get into the dictionary in the first place. you where assign them in the dictionary below

davidibitoye
Автор

Question: I'm confused because you are only adding elements and indices to the dict once you see that there is no counterpart for it. In the video, you were on i = 1 (2) and you said "we know we have a 6 (which would be T - a[i]), so that means it's in the dict. But how does 6 get in the dict if you haven't reached it in the for loop yet? Does the hash table/dict automatically add everything from the array BEFORE the loop starts? Because otherwise I don't understand how 6 was already in the dict before you had reached it in the loop to check for a counterpart and then add it to the dict as referenced on line 6. Would it not be that you have to add 2 to the dict since we don't yet know about 6, and then when we get to 6, we check the dict and find 2, thus returning these two indices? Please clarify, it would be very helpful.

NCJHE
join shbcf.ru