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

Поділитися
Вставка
  • Опубліковано 20 січ 2025

КОМЕНТАРІ • 132

  • @butteredtequilla9046
    @butteredtequilla9046 Рік тому +31

    You have just gained a subscriber. Out of all videos, this is so far the most comprehensible explanation. Thank you kind sir!!

    • @nikoo28
      @nikoo28  Рік тому +2

      Welcome aboard! Your feedback and love is much appreciated. Keeps me motivated :D

    • @ZachDift-kc4nk
      @ZachDift-kc4nk 7 місяців тому +1

      did this code work when you submitted it on leetcode?

    • @butteredtequilla9046
      @butteredtequilla9046 7 місяців тому

      @@ZachDift-kc4nk I can’t remember honestly it was a long time ago

  • @ngm-oe8ow
    @ngm-oe8ow Рік тому +33

    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 Рік тому

      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 Рік тому +11

      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 Рік тому

      True, my bad.@@ngm-oe8ow

    • @bobaGogo
      @bobaGogo Рік тому +5

      @@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 Рік тому

      why nlogn time complexity in 2sum using 2 pointer
      @@bobaGogo

  • @RakshithVrishab-ht8vk
    @RakshithVrishab-ht8vk Рік тому +4

    Simple ,yet optimized , thanks Nikhil!

  • @anoopghildiyal6413
    @anoopghildiyal6413 8 місяців тому +10

    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??

    • @SRC_ARENA
      @SRC_ARENA 5 місяців тому +1

      Using a HashMap, the complexity for TwoSum will be O(N). Without sorting only it can be done.

    • @AyushSharma-vq5ix
      @AyushSharma-vq5ix 3 місяці тому

      i think the same thing, TC should be O(nlogn) + O(n) , SC= O(n)

  • @Satya-g5t
    @Satya-g5t 4 місяці тому

    Really appreciate the effort you put into making other people understand. It is great service.

  • @YorozuyaNeesan2010
    @YorozuyaNeesan2010 3 місяці тому +1

    Thank you very much for your clear explanations and for drawing things out.

  • @ShahidHussain-dh3pg
    @ShahidHussain-dh3pg 4 місяці тому +1

    Amazing explanation. You redefined the meaning of comprehensive😎

  • @AaliyahJohnson-d6c
    @AaliyahJohnson-d6c 3 місяці тому +1

    Best explanation I've watched. Thank you!

    • @nikoo28
      @nikoo28  3 місяці тому

      Awesome, thank you!

  • @FnuAdnan
    @FnuAdnan 3 місяці тому

    Waouh, I was really lost with that problem but you explained it so well that I understand now. Thanks!

  • @jbr.1
    @jbr.1 Місяць тому +2

    I liked your way of teaching. Subscribed!!

    • @nikoo28
      @nikoo28  Місяць тому

      I'm glad you liked it. More videos coming soon!

  • @AbhishekKumar-hi8oj
    @AbhishekKumar-hi8oj Рік тому +1

    very nice explanation, before that i went through couple of video to understand properly but this time I understood . Thanks.

  • @architagarwal7379
    @architagarwal7379 10 місяців тому +4

    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  9 місяців тому +1

      O(n^2) will be dominant

    • @NIGHTSHADE123
      @NIGHTSHADE123 4 місяці тому

      @@nikoo28 we are sorting the array so complexity should be 0(n2 logn)

    • @benji-t7v
      @benji-t7v 2 місяці тому

      I think sorting us just done once so nsquared + logn which reduces to n2

  • @yadavom2001
    @yadavom2001 3 місяці тому +2

    Beautifully explained 😊

  • @michaeljohnbritto8399
    @michaeljohnbritto8399 4 місяці тому +1

    thanks for your fantastic explaination with simple code.

  • @imdarkseid2343
    @imdarkseid2343 6 місяців тому +2

    you did well soldier,nice approach simple and elegant but the duplicates numbers in arrays has to skipped to increase the faster execution

  • @gayiii1911
    @gayiii1911 2 місяці тому +1

    Thankyou sir, great explanation i understood very well

  • @checkraiser100
    @checkraiser100 7 місяців тому +2

    Damn, this video made the problem super easy

  • @NeelakshiSachdeva
    @NeelakshiSachdeva 6 місяців тому +3

    Girl did 2 sum and 3 sum today!! Keep going, faang is waiting for me

    • @nikoo28
      @nikoo28  6 місяців тому +2

      You can do it!

  • @bhaskarverma9810
    @bhaskarverma9810 15 годин тому

    Thanks for video , can you explain this problem -4 Sum - Find any quadruplet having given sum.

  • @shabanafirdose4671
    @shabanafirdose4671 Рік тому +3

    Too good , Thank you for sharing your knowledge

    • @nikoo28
      @nikoo28  Рік тому

      glad i could help you!!

  • @samridhshubham8109
    @samridhshubham8109 Рік тому

    Very Excellent solution, was stuck in this prob for hrs

  • @hinocenciopaulo
    @hinocenciopaulo 7 місяців тому +2

    Best approach.

  • @Babas420
    @Babas420 Рік тому

    great explanation, congratulations on putting in this effort!!!

    • @nikoo28
      @nikoo28  Рік тому

      Glad you enjoyed it!

  • @oknokok
    @oknokok 6 місяців тому

    Nice explanation, setup and video quality 📸

  • @nicedoodly6392
    @nicedoodly6392 3 місяці тому

    one of the best UA-camr

  • @viveknamdev2605
    @viveknamdev2605 3 місяці тому +1

    Thanks Sir For Solution

  • @Mano_Vikas
    @Mano_Vikas Рік тому

    You said, for viola in between at 5:22. What does that mean? Just curious

    • @nikoo28
      @nikoo28  Рік тому

      Means kind of ‘wow’ as an exclamation

  • @jataman123
    @jataman123 10 місяців тому +1

    How does this solution ensures that we don't use one value multiple times?

    • @nikoo28
      @nikoo28  10 місяців тому

      because all 3 pointers point at different indexes

  • @Dadu-g4r
    @Dadu-g4r Рік тому +2

    Amazing explanation 🔥

    • @nikoo28
      @nikoo28  Рік тому

      Thank you 🙌 😄

  • @MadhavanMan
    @MadhavanMan Рік тому +4

    The code takes 672 Runtime.Whether it is optimal

  • @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

  • @SanskrutiKanse
    @SanskrutiKanse 2 місяці тому

    Well explained❤ helpful!!!!

  • @theexplorerayesha
    @theexplorerayesha 4 місяці тому

    The best and simplest explanation and code I found on UA-cam 🥹 thank you so much sir

  • @ghayoorhussain8930
    @ghayoorhussain8930 Рік тому

    Crystal Clear Explanation Sir

  • @venkateshdhanasekaran5398
    @venkateshdhanasekaran5398 5 місяців тому

    After seeing lot many videos, finally I found the crystal clear approach.. Thank you so much brother. One question, how you handle the duplicate element in this?

    • @nikoo28
      @nikoo28  5 місяців тому

      I am using a HashSet, that takes care of duplicates

  • @sumitkaranjkar3819
    @sumitkaranjkar3819 5 місяців тому

    what about edge cases
    like all +ve or all -ve or all 0
    where you have to return {}, {}, {0,0,0} respectively

  • @plutomessi21
    @plutomessi21 Рік тому

    thank you bhaiya , i was stuck in this since yesterday

  • @melk48111
    @melk48111 Рік тому

    Great work Nikhil

  • @meriyemelhajoui4083
    @meriyemelhajoui4083 Рік тому

    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  Рік тому

      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.

  • @kchemutai3483
    @kchemutai3483 7 місяців тому

    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.

  • @shrutisrivastava5530
    @shrutisrivastava5530 8 місяців тому

    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?

  • @karthikmalode-ir5tw
    @karthikmalode-ir5tw 6 місяців тому

    Great solution ..understandable

  • @mayankkumargiri1289
    @mayankkumargiri1289 7 місяців тому

    13:06 If you're not taking any extra space at all, the space complexity should be O(1)

    • @nikoo28
      @nikoo28  6 місяців тому

      i misspoke, you are taking the space of the HashSet which has a size (n). Hence O(n).
      Thanks for the correction.

  • @Babas420
    @Babas420 Рік тому

    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  Рік тому

      it is constant space.

  • @architagarwal7379
    @architagarwal7379 10 місяців тому

    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

  • @IndianHistoryInDetails
    @IndianHistoryInDetails 2 місяці тому +1

    Using Hashet increases the time a lot we are gettinh 800 ms execution time.
    we can use below to reduce it.
    class Solution {
    public List threeSum(int[] nums) {

    if(nums.length

  • @rukhsanakhan9542
    @rukhsanakhan9542 7 місяців тому

    dil se pyaar aapko sir

  • @gireeswar18
    @gireeswar18 7 місяців тому

    Perfect Video !!!

  • @ZachDift-kc4nk
    @ZachDift-kc4nk 7 місяців тому

    does this solution actually work in leetcode? i am getting an error when i submit (not run) the code.

    • @nikoo28
      @nikoo28  7 місяців тому

      yes it does, check out the complete implementation on the Github link available in video description

  • @purnimahianl5678
    @purnimahianl5678 Рік тому

    You explain very well 👏

  • @AzharKhan-e9m
    @AzharKhan-e9m 6 місяців тому

    isme ek problem hai duplicate triplets ko lekr ... triplets double print horhe

  • @SamSafi003
    @SamSafi003 Рік тому +1

    Thank you ... ❤

  • @rishikakoul6336
    @rishikakoul6336 10 місяців тому +1

    CAN ANYONE EXPLAIN ME WHY HE DID ELSEIF(SUM

    • @sumitkaranjkar3819
      @sumitkaranjkar3819 5 місяців тому

      as he explained we need to adjust the index as per the sum
      ex- if sum

  • @kshitijpandey9376
    @kshitijpandey9376 Рік тому

    Understood the solution very well. Thank you

  • @hoddybhaba6704
    @hoddybhaba6704 Рік тому

    Easy to understand!!!

  • @sandeepkashyap7239
    @sandeepkashyap7239 Рік тому

    great
    great explanation

  • @anuragdutt36
    @anuragdutt36 11 місяців тому

    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 10 місяців тому +1

      to skip duplicates thats why he uses hashset

  • @AteebTahir-z1i
    @AteebTahir-z1i 6 місяців тому

    but how to handl eduplicates

    • @nikoo28
      @nikoo28  6 місяців тому

      that is why a hashset is used

  • @hajarelalit
    @hajarelalit Рік тому

    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 !

  • @rupeshpatil6957
    @rupeshpatil6957 4 місяці тому

    Thanks Brother

  • @GouravKumar-r2p
    @GouravKumar-r2p Рік тому +2

    Nikhil We want 4sum leetcode solution.

  • @user-qy2fm3pu2b
    @user-qy2fm3pu2b 6 місяців тому

    great man

  • @mikedelta658
    @mikedelta658 Рік тому +1

    Thank you

  • @harshitha5929
    @harshitha5929 Рік тому

    Good evening sir
    Thank you for such a keen explanation. Sir can you do leetcode problems on python 😊

  • @asr.explores
    @asr.explores Рік тому

    well explained

  • @arambh-gaur
    @arambh-gaur 4 місяці тому

    This is a good solution but the use of Set and then copying it back into a list is increasing the time complexity further, you fail to take that into account, on leetcode this solution takes more than 800ms which will not be good enough to clear the interview where they are expecting the optimal solution. Maybe you should also post how well your solutions perform compared to others on leetcode.

  • @omkar._.k
    @omkar._.k Рік тому +1

    Perfect

  • @VIJAYMAMORIA-c8m
    @VIJAYMAMORIA-c8m 7 місяців тому

    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  7 місяців тому

      That is why I sort the array. :)

    • @VIJAYMAMORIA-c8m
      @VIJAYMAMORIA-c8m 7 місяців тому +1

      @@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;
      }

  • @Jaylight977
    @Jaylight977 Рік тому

    Bro please bring more video on trees and graph

    • @nikoo28
      @nikoo28  Рік тому +1

      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.

    • @MadhavanMan
      @MadhavanMan Рік тому

      @@nikoo28 Complete binary search problem series

    • @nikoo28
      @nikoo28  11 місяців тому

      The complete playlist on graphs is now available: ua-cam.com/play/PLFdAYMIVJQHNFJQt2eWA9Sx3R5eF32WPn.html

  • @ShantanuSaha-vo6zh
    @ShantanuSaha-vo6zh 4 місяці тому

    Notice that the solution set must not contain duplicate triplets. Your solution will return duplicate triplets. For example: [-2,0,0,2,2]

    • @nikoo28
      @nikoo28  4 місяці тому

      we do handle duplicates. What output did you get with this test case?

  • @codeit3
    @codeit3 5 місяців тому

    thnks

  • @rgowtham9445
    @rgowtham9445 Рік тому

    good 🤩

  • @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 Рік тому +1

      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

  • @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 Рік тому

      he is storing it in a HashSet so it won't have duplicates.

    • @BharathVasudevan-s9u
      @BharathVasudevan-s9u 10 місяців тому

      Your videos are awesome, thanks for all the details. Can we avoid having the duplicates, like adding memorization? Is that possible?

    • @VIJAYMAMORIA-c8m
      @VIJAYMAMORIA-c8m 7 місяців тому

      You are correct. His solution is wrong. it wont remove duplicates.

  • @vinaypratapsingh339
    @vinaypratapsingh339 9 місяців тому

    if you sort the array, you will lost the indices.

    • @pradeepphulse4876
      @pradeepphulse4876 7 місяців тому +1

      But you need to return the values. Not the indexes.

  • @rawatbrothers0yt968
    @rawatbrothers0yt968 10 місяців тому +2

    why are you looking like young Narendra Modi

  • @vamshigud151
    @vamshigud151 7 місяців тому

    stock market bear bank side

  • @parthbhayana6326
    @parthbhayana6326 Рік тому

    Jo bhi bolo Hairfall toh bhot hogya 2 saalo me. 😂

    • @nikoo28
      @nikoo28  11 місяців тому

      can't escaping aging 😅

  • @joydeep_
    @joydeep_ 7 місяців тому

    Sorry to say, but not the best approach.

    • @nikoo28
      @nikoo28  6 місяців тому

      what would you suggest?

  • @ibrahim-abdallatif
    @ibrahim-abdallatif Рік тому

    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  11 місяців тому

      the solution I provided on my github profile does pass leetcode.

    • @satyaganesh7159
      @satyaganesh7159 11 місяців тому

      Set uses equals and hashcode to compare elements in it, so list1.equals(list2) compares each element sequentially