3 Sum (LeetCode 15) | Full solution with examples and visuals | Interview Essential

  Рет қаралды 55,459

Nikhil Lohia

Nikhil Lohia

Күн бұрын

To see more videos like this, you can buy me a coffee: www.buymeacoffee.com/studyalg...
Actual Problem: leetcode.com/problems/3sum/
Chapters:
00:00 - Intro
00:39 - Problem Statement and Description
02:45 - Brute Force Approach
04:21 - Similarity to Two Sum
05:45 - Building an efficient solution
10:28 - Dry-run of Code
13:17 - Final Thoughts
📚 Links to topics I talk about in the video:
Two Sum: • Two Sum (LeetCode #1) ...
Sorting Techniques: • Sorting Techniques
Brute Force Paradigm: • Brute Force algorithms...
📘 A text based explanation is available at: studyalgorithms.com
Code on Github: github.com/nikoo28/java-solut...
Test-cases on Github: github.com/nikoo28/java-solut...
📖 Reference Books:
Starting Learn to Code: amzn.to/36pU0JO
Favorite book to understand algorithms: amzn.to/39w3YLS
Favorite book for data structures: amzn.to/3oAVBTk
Get started for interview preparation: amzn.to/39ysbkJ
🎥 My Recording Gear:
Recording Light: amzn.to/3pAqh8O
Microphone: amzn.to/2MCX7qU
Recording Camera: amzn.to/3alg9Ky
Tablet to sketch and draw: amzn.to/3pM6Bi4
Surface Pen: amzn.to/3pv6tTs
Laptop to edit videos: amzn.to/2LYpMqn
💻 Get Social 💻
Follow on Facebook at: / studyalgos
Follow on Twitter at: / studyalgorithms
Follow on Tumblr at: / studyalgos
Subscribe to RSS feeds: studyalgorithms.com/feed/
Join fan mail: eepurl.com/g9Dadv
#leetcode #programming #interview

Пікірлер: 100
@RakshithVrishab-ht8vk
@RakshithVrishab-ht8vk 11 ай бұрын
Simple ,yet optimized , thanks Nikhil!
@butteredtequilla9046
@butteredtequilla9046 Жыл бұрын
You have just gained a subscriber. Out of all videos, this is so far the most comprehensible explanation. Thank you kind sir!!
@nikoo28
@nikoo28 Жыл бұрын
Welcome aboard! Your feedback and love is much appreciated. Keeps me motivated :D
@ZachDift-kc4nk
@ZachDift-kc4nk 29 күн бұрын
did this code work when you submitted it on leetcode?
@butteredtequilla9046
@butteredtequilla9046 21 күн бұрын
@@ZachDift-kc4nk I can’t remember honestly it was a long time ago
@ngm-oe8ow
@ngm-oe8ow 10 ай бұрын
If you sort the array the complexity becomes O(nLog(n)) in the 2 sum part and you said the complexity becomes o(n), but for the 3sum sorting is okay because you are reducing it to o(n^2). The explanation was quite good and understandable thanks.
@peasantfaye5403
@peasantfaye5403 10 ай бұрын
It's not like you sort an array n times in sum2, however. You sort an array once, then you iterate through it in O(n) time. You could say it's O(n + log(n)), but it's still linear time, so we simplify it to O(n).
@ngm-oe8ow
@ngm-oe8ow 10 ай бұрын
With the inbuilt sorting or any sorting algorithm it would take O(nlog(n)) not O(log(n)) time. so O(nlog(n)+n)) simplifies to O(nlog(n)). so it's not linear time. it would take linear time if you use hashing.
@peasantfaye5403
@peasantfaye5403 10 ай бұрын
True, my bad.@@ngm-oe8ow
@bobaGogo
@bobaGogo 9 ай бұрын
@@peasantfaye5403 you can only solve 2 sum in O(n) with a hashmap. If you do the 2 pointer solution you will get a O(1) space complexity, but O(n*log(n)) time complexity.
@GaganSingh-zz9el
@GaganSingh-zz9el 5 ай бұрын
why nlogn time complexity in 2sum using 2 pointer @@bobaGogo
@anoopghildiyal6413
@anoopghildiyal6413 Ай бұрын
At 5:30 how the time complexity is O(n)?? you have sorted the array so it would be O(nlogn) already for the sorting so how it would be O(n) for total algorithm??
@ghayoorhussain8930
@ghayoorhussain8930 Жыл бұрын
Crystal Clear Explanation Sir
@AbhishekKumar-hi8oj
@AbhishekKumar-hi8oj 10 ай бұрын
very nice explanation, before that i went through couple of video to understand properly but this time I understood . Thanks.
@nikoo28
@nikoo28 10 ай бұрын
glad I could help
@hinocenciopaulo
@hinocenciopaulo Ай бұрын
Best approach.
@samridhshubham8109
@samridhshubham8109 10 ай бұрын
Very Excellent solution, was stuck in this prob for hrs
@nikoo28
@nikoo28 9 ай бұрын
glad I could help
@sysybaba420
@sysybaba420 9 ай бұрын
great explanation, congratulations on putting in this effort!!!
@nikoo28
@nikoo28 9 ай бұрын
Glad you enjoyed it!
@shabanafirdose4671
@shabanafirdose4671 Жыл бұрын
Too good , Thank you for sharing your knowledge
@nikoo28
@nikoo28 Жыл бұрын
glad i could help you!!
@oknokok
@oknokok 10 сағат бұрын
Nice explanation, setup and video quality 📸
@karthikmalode-ir5tw
@karthikmalode-ir5tw 5 күн бұрын
Great solution ..understandable
@plutomessi21
@plutomessi21 11 ай бұрын
thank you bhaiya , i was stuck in this since yesterday
@RN-jo8zt
@RN-jo8zt 6 ай бұрын
i got it that nums.length - 2 in the loop condition is to ensure that there are at least two elements to the right of the current index i even i can find triplet with for (int i = 0; i < nums.length ; i++) { insted of for (int i = 0; i < nums.length -2; i++) { so is there any reason we are writing -2?
@purnimahianl5678
@purnimahianl5678 11 ай бұрын
You explain very well 👏
@supershinobi7892
@supershinobi7892 Жыл бұрын
your explanation is awesome thank you brother i was not able to solve this question before your video Now i solved.
@nikoo28
@nikoo28 Жыл бұрын
You are most welcome
@melk48111
@melk48111 8 ай бұрын
Great work Nikhil
@gireeswar18
@gireeswar18 26 күн бұрын
Perfect Video !!!
@checkraiser100
@checkraiser100 Ай бұрын
Damn, this video made the problem super easy
@user-hp9kj8qt1h
@user-hp9kj8qt1h 12 күн бұрын
Girl did 2 sum and 3 sum today!! Keep going, faang is waiting for me
@nikoo28
@nikoo28 11 күн бұрын
You can do it!
@hoddybhaba6704
@hoddybhaba6704 Жыл бұрын
Easy to understand!!!
@user-pv8pk4lh5i
@user-pv8pk4lh5i Жыл бұрын
Amazing explanation 🔥
@nikoo28
@nikoo28 Жыл бұрын
Thank you 🙌 😄
@user-gn6ld5to8m
@user-gn6ld5to8m 6 ай бұрын
Thank you ... ❤
@sandeepkashyap7239
@sandeepkashyap7239 Жыл бұрын
great great explanation
@rukhsanakhan9542
@rukhsanakhan9542 24 күн бұрын
dil se pyaar aapko sir
@architagarwal7379
@architagarwal7379 3 ай бұрын
Time complexity is O[n^2logn]. We have to use hashmap apprach of 2 sum if the array is not sorted by default
@nikoo28
@nikoo28 2 ай бұрын
O(n^2) will be dominant
@shrutisrivastava5530
@shrutisrivastava5530 Ай бұрын
The solution was very simple to understand thankyou so much. But i had a doubt as I implemented this on leetcode, the time it took for all the test cases was: 457ms , and 9ms solutions were also available. So I have to study the more optimum approach or it is fine for technical round or interview round?
@mikedelta658
@mikedelta658 6 ай бұрын
Thank you
@harshitha5929
@harshitha5929 10 ай бұрын
Good evening sir Thank you for such a keen explanation. Sir can you do leetcode problems on python 😊
@asr.explores
@asr.explores 7 ай бұрын
well explained
@Mano_Vikas
@Mano_Vikas 6 ай бұрын
You said, for viola in between at 5:22. What does that mean? Just curious
@nikoo28
@nikoo28 6 ай бұрын
Means kind of ‘wow’ as an exclamation
@omkar._.k
@omkar._.k 5 ай бұрын
Perfect
@kshitijpandey9376
@kshitijpandey9376 6 ай бұрын
Understood the solution very well. Thank you
@sysybaba420
@sysybaba420 9 ай бұрын
you are using a set to arrive at a solution right? so how do you say that you are not using any extra space? or is it just constant space?
@nikoo28
@nikoo28 9 ай бұрын
it is constant space.
@hajarelalit
@hajarelalit 5 ай бұрын
Nice solution, I have now subscribed to your channel, very good explanation and solution. I want to clear Toptal interview, please guide me in some way if possible. Thanks !
@kchemutai3483
@kchemutai3483 23 күн бұрын
Great explanation, I just wanted a clarification on the time complexity, i think we left out the time complexity for sorting. What is the time complexity for sorting, otherwise the rest is O(n^2) as explained.
@user-do6rh1ev4k
@user-do6rh1ev4k Жыл бұрын
The code takes 672 Runtime.Whether it is optimal
@rgowtham9445
@rgowtham9445 Жыл бұрын
good 🤩
@jataman123
@jataman123 4 ай бұрын
How does this solution ensures that we don't use one value multiple times?
@nikoo28
@nikoo28 3 ай бұрын
because all 3 pointers point at different indexes
@ZachDift-kc4nk
@ZachDift-kc4nk 29 күн бұрын
does this solution actually work in leetcode? i am getting an error when i submit (not run) the code.
@nikoo28
@nikoo28 28 күн бұрын
yes it does, check out the complete implementation on the Github link available in video description
@architagarwal7379
@architagarwal7379 3 ай бұрын
Nice explanation but there are 2 cases over here. if the array is sorted already or the array is not sorted. if the array is sorted we can go with the approach explained by nukhil but if its not sorted the better use hashmap approach which gives O[n] TC and O[N] SC
@NeerajManoj
@NeerajManoj Жыл бұрын
nice bro
@rishikakoul6336
@rishikakoul6336 3 ай бұрын
CAN ANYONE EXPLAIN ME WHY HE DID ELSEIF(SUM
@meriyemelhajoui4083
@meriyemelhajoui4083 7 ай бұрын
I dont see what we should sort the array ? if we gonna loop over the loop and everytime fix and try to found a sum that s equal to 0
@nikoo28
@nikoo28 6 ай бұрын
Sorting the array ensures that all smaller numbers are to the left abd larger to the right. Then you look at the sum obtained…if greater than target, then you need to pick a smaller number..so just move the right pointer by 1 place instead of traversing the entire array. Saves you a lot of time.
@mayankkumargiri1289
@mayankkumargiri1289 19 күн бұрын
13:06 If you're not taking any extra space at all, the space complexity should be O(1)
@nikoo28
@nikoo28 11 күн бұрын
i misspoke, you are taking the space of the HashSet which has a size (n). Hence O(n). Thanks for the correction.
@user-lb7kn2bh5n
@user-lb7kn2bh5n Жыл бұрын
Nikhil We want 4sum leetcode solution.
@TuringTested01
@TuringTested01 Жыл бұрын
I think one more optimization you can do is this: Keeping a boolean array of "done" numbers and marking the numbers with which triplets are already made, because there could be duplicates of each number and for each of them you dont have to find the triplets because triplets would be unique, for example: if there is an array of 3000 integers all containing zero, your code would go to every zero and find the triplets using all zeros whereas the answer would just be [0,0,0]
@gauratomar
@gauratomar 10 ай бұрын
In this way some cases would be lost as -1, 0,1 and 2,-1, -1 are also there both use -1 and both are different trplets
@jayprakashjaiswal8220
@jayprakashjaiswal8220 Жыл бұрын
Bro please bring more video on trees and graph
@nikoo28
@nikoo28 Жыл бұрын
i am adding more and more videos every week. I am myself limited by resources and time. Hope you understand...if you have a particular topic/question in mind, let me know..and I can add it to my video list.
@user-do6rh1ev4k
@user-do6rh1ev4k Жыл бұрын
@@nikoo28 Complete binary search problem series
@nikoo28
@nikoo28 5 ай бұрын
The complete playlist on graphs is now available: kzbin.info/aero/PLFdAYMIVJQHNFJQt2eWA9Sx3R5eF32WPn
@anurag_dutt
@anurag_dutt 4 ай бұрын
Bhaiya, the explanation is so good but we have to skip the duplicate triplets. So, we have to do this If (i>0 && nums[i]==nums[i-1]){ Continue; } Duplicate triplets are the question [-4,-1,-1,0,1,2] are See the [-1(1 idx),0,1] and [-1(2 idx),0,1].. Thank you.❤
@Prm906
@Prm906 3 ай бұрын
to skip duplicates thats why he uses hashset
@AzharKhan-e9m
@AzharKhan-e9m 9 күн бұрын
isme ek problem hai duplicate triplets ko lekr ... triplets double print horhe
@user-ph5ek8tg5l
@user-ph5ek8tg5l Ай бұрын
Bro, Your solution is wrong where you are assuming that HashSet will remove duplicate Lists. {1,2,3} & {3,2,1} are two different lists. They wont be considered duplicate by the HashSet as List equals method wont return equal for both. Set result = new HashSet(); result.add(Arrays.asList(1, 2, 3)); result.add(Arrays.asList(3, 2, 1)); System.out.println(result.size()); // Prints 2 NOT 1
@nikoo28
@nikoo28 Ай бұрын
That is why I sort the array. :)
@user-ph5ek8tg5l
@user-ph5ek8tg5l Ай бұрын
@@nikoo28 Ok. got it. Since always the sorted List is added to the Set duplicate list addition is taken care of by the Set. But we can optimize the solution to avoid trying to add even those duplicate lists. int twoSum = A[left] + A[right]; if (twoSum == sum) { triplets.add(Arrays.asList(A[i], A[left], A[right])); /** * Only if we have found a solution for two values we can be sure we should move ahead of all their * duplicates. */ while (left < right && A[left + 1] == A[left]) { ++left; } ++left; while (left < right && A[right - 1] == A[right]) { --right; } --right; }
@vamshigud151
@vamshigud151 Ай бұрын
stock market bear bank side
@SuriyaT3001
@SuriyaT3001 Жыл бұрын
This is not right .. pls check it out it gives duplicate output but in question they asked only unique subsets.. while dry run of your code pls execute in leet code itself ..
@nikoo28
@nikoo28 Жыл бұрын
check the code available on github in description. It does pass on leetcode.
@ngm-oe8ow
@ngm-oe8ow 10 ай бұрын
he is storing it in a HashSet so it won't have duplicates.
@user-fe8nh9kz7q
@user-fe8nh9kz7q 3 ай бұрын
Your videos are awesome, thanks for all the details. Can we avoid having the duplicates, like adding memorization? Is that possible?
@user-ph5ek8tg5l
@user-ph5ek8tg5l Ай бұрын
You are correct. His solution is wrong. it wont remove duplicates.
@vinaypratapsingh339
@vinaypratapsingh339 3 ай бұрын
if you sort the array, you will lost the indices.
@pradeepphulse4876
@pradeepphulse4876 29 күн бұрын
But you need to return the values. Not the indexes.
@rawatbrothers0yt968
@rawatbrothers0yt968 4 ай бұрын
why are you looking like young Narendra Modi
@parthbhayana6326
@parthbhayana6326 6 ай бұрын
Jo bhi bolo Hairfall toh bhot hogya 2 saalo me. 😂
@nikoo28
@nikoo28 4 ай бұрын
can't escaping aging 😅
@joydeep_
@joydeep_ 24 күн бұрын
Sorry to say, but not the best approach.
@nikoo28
@nikoo28 11 күн бұрын
what would you suggest?
@ibrahim-abdallatif
@ibrahim-abdallatif 6 ай бұрын
Thanks for the clear explanation, but please note that this solution allows duplicate triplets in the result, which is not correct and won't pass leetcode submission (I tried it myself), here is the correct solution after some changes: >>> EDIT: When I tried it I was using a LinkedList instead of a HashSet as shown in the video(using HashSet won't allow duplicates indeed and hence the presented solution is correct), anyway here is the correct way to solve it with LinkedList. class Solution { public List threeSum(int[] nums) { Arrays.sort(nums); List result = new LinkedList(); for (int i = 0; i < nums.length -2; i++) { if(i == 0 || (i > 0 && nums[i] != nums[i-1])) { int left = i + 1; int right = nums.length - 1; while(left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { result.add(Arrays.asList(nums[i], nums[left], nums[right])); while(left < right && nums[left+1] == nums[left]) left++; while(left < right && nums[right-1] == nums[right]) right--; left++; right--; } else if(sum < 0) { left++; } else { right--; } } } } return result; } } // TC: O(n^2), SC: O(n)
@nikoo28
@nikoo28 4 ай бұрын
the solution I provided on my github profile does pass leetcode.
@satyaganesh7159
@satyaganesh7159 4 ай бұрын
Set uses equals and hashcode to compare elements in it, so list1.equals(list2) compares each element sequentially
Khó thế mà cũng làm được || How did the police do that? #shorts
01:00
Вечный ДВИГАТЕЛЬ!⚙️ #shorts
00:27
Гараж 54
Рет қаралды 14 МЛН
MY ULTIMATE LEETCODE TRICKS
8:12
PIRATE KING
Рет қаралды 225 М.
Two Sum | LeetCode 1 | JavaScript | Easy
13:20
Gordon Zhu
Рет қаралды 8 М.
3 Sum | Brute -  Better - Optimal with Codes
38:25
take U forward
Рет қаралды 244 М.
4 Sum | Brute - Better - Optimal with Codes
28:47
take U forward
Рет қаралды 133 М.
Kadane's Algorithm | Maximum Subarray Sum | Finding and Printing
20:09
take U forward
Рет қаралды 327 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 237 М.
DSA Phir se with Sumeet | Leetcode 15 | 3Sum
18:03
Pepcoding
Рет қаралды 3,3 М.