TwoSum Java Code, HashMap approach. O^n HD

preview_player
Показать описание
Find two such numbers that add to a given target sum. Time and space complexity explained.
Рекомендации по теме
Комментарии
Автор

This is the best explanation I have came across. I never understood how complements worked until I watched this

Limpuls
Автор

Thank-you so much for such wonderful explanation, understood each and every line of code with perfection. Please continue posting many many such videos.

saileshramesh
Автор

Great Explanation.
Just an add-on thing, it's not passing for one condition when the array contains: [3, 2, 4] and target = 6.
It will return 0, 0 (instead of returning 1, 2)
In order to handle this case, just replace your if condition with this one:
if(h1.containsKey(target) && i != h1.get(target))

hadiali
Автор

We can see that complement comes out to be same element nums[i] which is at index 0 in given case hence it returned 0, 0.
As a solution, one can check if complement == nums[i] //given we have no duplicates allow.
Second solution, as I can see is that this can happen only when the nums[i] is targetSum/2. In case we have no duplicates allowed, we can add an if statement nums[i] == targetSum/2 then continue to next index without doing anything.

PS: I am not sure of my solutions though, haven't coded them yet. Newbie to Java. Correct me if I'm wrong somewhere.

PPS: Nice explanation and implementation.

VipinKumar-rvfw
Автор

how would, map if the array contains duplicates

abhiram
Автор

Please explain to me how the .getMethod is returning the Key value. to my understanding, .get(key) is suppose to return the value.

asahimojica
Автор

Good Explanation 😍😍
We have to Check other Condition in If loop i.e
& & map.get(compliment)!=i)

-YEDUKONDALU
Автор

It would fail if the target value lets say is 2 and first element of the array is 2.
2

gtxmax-q
Автор

Nice explanation mam.
I don't know why one gave dislike 😑

avisinha
join shbcf.ru