3 Sum | Brute - Better - Optimal with Codes

Sdílet
Vložit
  • čas přidán 5. 07. 2024
  • Problem Link: bit.ly/3X34JSI
    Notes/C++/Java/Python codes:
    We have solved the problem, and we have gone from brute force and ended with the most optimal solution. Every approach's code has been written in the video itself. Also, we have covered the algorithm with intuition.
    Full Course: bit.ly/tufA2ZYt
    You can follow me across social media, all my handles are below:
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    0:00 Introduction of Course
    00:41 Problem Statement
    02:56 Brute force approach (Using 3-pointer)
    04:55 Pseudocode
    07:36 Code
    09:27 Complexity
    10:26 Better approach (Using Hashing)
    12:23 Dry run
    18:09 Code
    20:15 Complexity
    22:20 Optimal approach (Using 2-pointer)
    23:20 2-Pointer Technique
    31:50 Code
    36:41 Complexity

Komentáře • 309

  • @takeUforward
    @takeUforward  Před rokem +115

    Please do give us a like and subscribe, it won't cost you anything, but it will motivate me to make such kind of content more and more.

    • @utsavseth6573
      @utsavseth6573 Před rokem +2

      Legendary stuff Raj bhai. Your explanation clearly shows you actually have a very strong depth on these fundamentals. And of course you do, you work for Google😉

    • @deepak8720
      @deepak8720 Před 11 měsíci +1

      Awesome stuff. Liked and subscribed. Keep going. 👍

    • @pardhi8959
      @pardhi8959 Před 9 měsíci +1

      great content love u bhai

    • @pardhi8959
      @pardhi8959 Před 9 měsíci +1

      I start by like for all the video

    • @Bhai9866
      @Bhai9866 Před 8 měsíci

      Bhaiya code nhi chal raha hai 3 sum ki u give the condition sum is greater than 0 , less than 0 but didn't give the condition sum is equal to 0 why?

  • @luckshaeey
    @luckshaeey Před rokem +192

    Tried 2 sum, 3 sum and 4 sum problems together as a beginner. It was so frustrating after a point before I understood the optimal approach 😂

    • @rishav144
      @rishav144 Před rokem +3

      true bro

    • @it-51gulshanbhati89
      @it-51gulshanbhati89 Před rokem +30

      u r strong bro u have tried all as a beginner 😅

    • @Akash-yr2if
      @Akash-yr2if Před rokem +12

      You have a lot more experience than the whole comment section combined.

    • @user-ye4xi4py2k
      @user-ye4xi4py2k Před 10 měsíci +3

      The optimal approach for 3sum is just the extension of optimal approach of 2 sum when the array given is sorted

    • @joeljacob4685
      @joeljacob4685 Před 10 měsíci

      @@user-ye4xi4py2k yup !! you are right

  • @rajatyadav4077
    @rajatyadav4077 Před 15 dny +6

    It's interesting-I initially tackled this problem with three nested loops, but when the time exceeded, I decided to find a way to eliminate one loop and ended up developing a two-pointer solution. Although I found the solution, I still enjoy watching Striver's videos to refresh my mind, spark creativity, and discover new approaches to problem-solving.

    • @karthikeyan.s2565
      @karthikeyan.s2565 Před 9 dny +3

      Bro 3 loops was the best I could think of, I can't able to optimize it
      How do you develop this logical thinking ?
      Could you help me with this ?

    • @user-hp9kj8qt1h
      @user-hp9kj8qt1h Před 5 dny +1

      Me too pls

  • @mehulthuletiya497
    @mehulthuletiya497 Před rokem +54

    00:41 Problem Statement
    02:56 Brute force approach (Using 3-pointer)
    04:55 Pseudocode
    07:36 Code
    09:27 Complexity
    10:26 Better approach (Using Hashing)
    12:23 Dry run
    18:09 Code
    20:15 Complexity
    22:20 Optimal approach (Using 2-pointer)
    23:20 2-Pointer Technique
    31:50 Code
    36:41 Complexity

  • @shashankrajput8084
    @shashankrajput8084 Před 2 měsíci +5

    That's what a explanation beginner require for these type of problems

  • @itzmartin20
    @itzmartin20 Před 9 měsíci +12

    Just cameback for a quick revision, and now it's indeed got into my head, thanks for your crystal clear intuition!

  • @Pamir026
    @Pamir026 Před 10 měsíci +8

    Yes! I was onto this optimal approach but my implementation failed because I wasn't thinking it through. Simply lovely explanation!

  • @deepak8720
    @deepak8720 Před 11 měsíci +3

    Completely Understood your explanation! Thank you for what you are doing, and please continue the good work. You are an amazing teacher. Have watched 3 videos of yours and I was able to understand all 3 with out any confusions. Big thumbs up for the video. 👍

  • @subhranshuswayampravadash4656

    Thanks brother for helping and providing us amazing solutions of the most important questions that asked in MNC's. Thanks a lot brother🙏

  • @pragyatripathi8833
    @pragyatripathi8833 Před rokem +6

    I love the way you teach bhayiya.❤❤ I don't have seen the teacher like you....you are God of DSA.

  • @abhijeetmishra3804
    @abhijeetmishra3804 Před 9 měsíci +2

    how can one explain so smoothly man...Hats of STRIVER bhaiya

  • @jeet-smokey
    @jeet-smokey Před 4 měsíci

    We will never get such a detailed explanation of 3 Sum problem. You are a Legend for reason....Striver.....!!!!

  • @PrashantSingh-qr3vn
    @PrashantSingh-qr3vn Před 10 měsíci +1

    Are u a genius how do u know what doubts a newbie would have . U r just superb in explaining the Algo

  • @ruchikaahujaasm
    @ruchikaahujaasm Před 2 měsíci +1

    Explained all 3 approaches very clearly. Thank you so much!!!

  • @cinime
    @cinime Před rokem +1

    Understood! Super amazing explanation as always, thank you very much for your effort!!

  • @AmartyaPardeshi
    @AmartyaPardeshi Před 10 měsíci +3

    My man is doing God's work, thanks for this amazing playlist!

  • @Manishgupta200
    @Manishgupta200 Před rokem

    Thanks for the in-depth explaination with in-depth time and space complexity

  • @swathigp3818
    @swathigp3818 Před 2 měsíci +2

    Great examples, which helps understand the algorithm very clearly even for non CSE folks!!

  • @trinitykhuman
    @trinitykhuman Před 6 měsíci

    I was looking for brute force approach tried myself but couldn't remember I have to used set DS but now , I can understand where I was wrong. Thanks for the tutorial.

  • @sharmavishal7239
    @sharmavishal7239 Před rokem

    Bhai maine aapki dsa sheet aaj first time dekhi hai
    kya banayi hai bhai , sach main mja aa gya ....
    Thanku dil se striver bhai ❤

  • @sdakshin1
    @sdakshin1 Před měsícem

    I found your explanation the best among all available... gd job

  • @ahssanakhtar5746
    @ahssanakhtar5746 Před 13 dny

    Amazing content learn a lot every day from your course.Thanks for creating such an amazing course.

  • @RahulKumar-zp1ln
    @RahulKumar-zp1ln Před 10 měsíci

    THANK YOU FOR EXPLANING IN SIMPLE WAY

  • @user-bj9qx9yf1o
    @user-bj9qx9yf1o Před 10 měsíci +1

    Hi, you are doing extremely good work DSA topics. You making concepts very clear. Glad that I got your channel reference. But un luckily I am from JavaScript background , i am finding a resources like anything for DSA, I dint get any . Your help will be appreciated on this.

  • @piyushroy3278
    @piyushroy3278 Před dnem

    Too good man, more and more kudos to you for such explanation. now im getting grip on building logic...finally.

  • @disciplines4
    @disciplines4 Před rokem

    nice all the three approaches, helped a lot.

  • @rohansingh6329
    @rohansingh6329 Před 11 měsíci

    awsm video striver ❤❤ the free education you are providing is helping a us alot.

  • @S__Arslaan
    @S__Arslaan Před 9 měsíci +1

    no need of condtion j

  • @welcometoc.s.easpirants
    @welcometoc.s.easpirants Před 7 měsíci

    Awesome explaination. Thank u for such a great content.

  • @jingfulin2322
    @jingfulin2322 Před 3 měsíci

    Great job! your code is so clean.

  • @Bakwas_baate
    @Bakwas_baate Před měsícem

    what a solution. MINDBLOWING!!!!

  • @culeforever5408
    @culeforever5408 Před 8 měsíci +1

    understood and came up with the optimal solution myself almost same. just used an extra set to store triplets 😅

  • @eashan2405
    @eashan2405 Před 10 měsíci +1

    Great explanation Striver ❤

  • @priyanshuagrawal7509
    @priyanshuagrawal7509 Před 7 měsíci +1

    Now i can finally answer someone if someone ask me have you done 3Sum 😆. Thanks Striver 😉

  • @joeljacob4685
    @joeljacob4685 Před 10 měsíci

    Beautiful dry run!! Understood😄

  • @gamingchampions4105
    @gamingchampions4105 Před 9 měsíci

    gained a subscriber with your amazing explanation

  • @impalash_ag
    @impalash_ag Před 4 dny

    Hi Raj, there are 2 slight mistakes in your optimal solution.
    1: The for loop will run till n-2 instead of n, because when i=n-1, j becomes n (j=i+1=n-1+1) and num[j] throws out of bound exception.
    2: We could also insert another check in the for loop(nums[i] = 1 there's no way any 3 elements sum would be 0 since the array is now sorted.
    3: Here's the more readable code(JAVA):
    class Solution {
    public List threeSum(int[] nums) {
    int n = nums.length;
    List result = new ArrayList();
    Arrays.sort(nums);
    for(int i=0; i low && nums[high] == nums[high+1])
    high--;
    }
    else {
    result.add(Arrays.asList(nums[i], nums[low], nums[high]));
    low++;
    high--;
    while(low < high && nums[low] == nums[low-1])
    low++;
    while(high > low && nums[high] == nums[high+1])
    high--;
    }
    }
    }
    }

  • @Benstokes555
    @Benstokes555 Před 5 měsíci

    mind blown, dopamine released, love u striver

  • @JackCoderr
    @JackCoderr Před rokem

    Thank you so much bhaiya....you are the best teacher ❤❤❤

  • @dipingrover1970
    @dipingrover1970 Před 4 měsíci

    amazing exlanation , loved this video

  • @sarangkumarsingh7901
    @sarangkumarsingh7901 Před 3 měsíci

    Another Awesome Lecture................

  • @user-yz6yk4vt6q
    @user-yz6yk4vt6q Před 4 měsíci

    what a fantastic explantion!!!!

  • @samlinus836
    @samlinus836 Před rokem

    Thank you bro, love from Tamil Nadu ❤

  • @rahulraaja5056
    @rahulraaja5056 Před 10 měsíci +1

    Great Explanation 💯💯

  • @manvendrasingh4369
    @manvendrasingh4369 Před 21 dnem

    While solving this problem, the very first approach which comes to my mind was optimal. Although the way I was handling duplicates was giving time limit exceeded error so I have to took help from gpt but rest of the logic was correct. Feeling extremely happy.

  • @bipinmaharjan4090
    @bipinmaharjan4090 Před 3 měsíci

    Bro that hash map solution is so genius.

  • @a1_32_aarushi8
    @a1_32_aarushi8 Před rokem

    Thank you so much sir for such a nice explanation your are super sir❤

  • @anjigolla4853
    @anjigolla4853 Před rokem

    superb explanation brother👏

  • @sayantanpoddar5428
    @sayantanpoddar5428 Před 7 měsíci

    understood!!! please came up with string series...please

  • @konankikeerthi
    @konankikeerthi Před 25 dny

    Understood bro. Thank you

  • @tanya8353
    @tanya8353 Před 6 měsíci

    Great Job again !!

  • @sayakghosh5104
    @sayakghosh5104 Před rokem +1

    Awesome explanation....

  • @souravmehraniya2832
    @souravmehraniya2832 Před rokem +1

    Keep going brother ❤

  • @udaytewary3809
    @udaytewary3809 Před rokem

    Understood bhaiya 🙏 ❤️

  • @anasnadeem3259
    @anasnadeem3259 Před 11 měsíci

    Great explanation 💯

  • @Azeem_Idrisi
    @Azeem_Idrisi Před rokem

    Amazing explanation 👌💯

  • @nightgamer8953
    @nightgamer8953 Před 8 měsíci

    HashSet in C# still stores duplicate List in C# . Is there any alternatives in C# to store unique List of Integers?

  • @priyankaghosh2670
    @priyankaghosh2670 Před rokem

    best teacher in the world...........

  • @ru2979
    @ru2979 Před rokem +12

    never got an opportunity to do 3sum 😢 koi na LC pe hi krleta hu 🙂 seh lenge

  • @tarunsingh7826
    @tarunsingh7826 Před rokem

    Best explanation 🔥

  • @arunprashanna7494
    @arunprashanna7494 Před 10 měsíci

    Perfect explanation

  • @anuragprasad6116
    @anuragprasad6116 Před 4 měsíci +3

    3-sum code using 2 for loops and 1 while loop. Using for loops helps in more readability in this problem.
    // Sort the vector and create ans array.
    sort(arr.begin(), arr.end());
    vector ans;
    // Iterate the sorted array.
    for (int i = 0; i < n; i++) {
    // Make sure first element of triplet is unique.
    // Now whole array on right of 'i' is a 2-sum problem.
    if (i > 0 && arr[i] == arr[i-1]) continue;
    // Take -ith element as target.
    int twosum = -arr[i];
    int right = n-1;
    // Look for unique 2nd element in the search space. Notice that for
    // each unique i, the pairs that create 3sum with it are unique.
    // Similarily, for each unique j, the 3rd element will be unique.
    for (int j = i+1; j < right; j++) {
    // Looking only for unique 2nd element.
    if (j > i+1 && arr[j] == arr[j-1]) continue;
    // Look for its partner.
    while (j < right && arr[j] + arr[right] > twosum) right--;
    // No need to skip. All the 2nd elements are unique!
    if (arr[j] + arr[right] == twosum && j != right)
    ans.push_back({arr[i], arr[j], arr[right]});
    }
    }
    return ans;
    Similarily, 4sum can be broken down as: first unique element + 3sum in remaining search space.

  • @AbhishekKumar-nz9dn
    @AbhishekKumar-nz9dn Před 9 měsíci

    understood brilliantly 😘

  • @anmjubaer
    @anmjubaer Před 7 měsíci +1

    Great explanation but what about the time complexity of those 2 while loops from the optimal solution? Can you elaborate a bit here please?

  • @NazeerBashaShaik
    @NazeerBashaShaik Před 3 měsíci

    Understood, thank you.

  • @swacharahman5084
    @swacharahman5084 Před rokem

    Thank you bhaiya, Love from bangladesh

  • @sonalitribhuvan3409
    @sonalitribhuvan3409 Před rokem

    Awesome explanation

  • @UECAshutoshKumar
    @UECAshutoshKumar Před měsícem +1

    Understood 👍

  • @hashcodez757
    @hashcodez757 Před měsícem

    Mza aagya
    Understood!!

  • @GhostVaibhav
    @GhostVaibhav Před 4 měsíci +1

    Understood🔥

  • @vishalgupta7522
    @vishalgupta7522 Před rokem +2

    Line 29: Char 10: error: type 'vector' does not provide a call operator
    ans(st.begin(), st.end());
    ^~~
    1 error generated. brute force code

  • @AniketKumar-hf2bo
    @AniketKumar-hf2bo Před 5 měsíci

    understood ,thnx for explanation ❤❤❤❤❤❤👌👌💕💕💕💕

  • @aditikaushik3073
    @aditikaushik3073 Před 11 měsíci

    Thanks a lot, sir !!

  • @ruchirtd1
    @ruchirtd1 Před rokem +5

    Understood!
    Java Solution that is accepted on Leetcode:
    class Solution {
    public List threeSum(int[] nums) {
    Set res = new HashSet();
    Arrays.sort(nums);
    for(int i=0;i

  • @amankumar5230
    @amankumar5230 Před 10 měsíci

    Sir,
    Please continue your solution videos for A-Z DSA course

  • @dpxy1599
    @dpxy1599 Před 9 měsíci

    got it nicely explained.

  • @sahulraj9536
    @sahulraj9536 Před 4 měsíci

    we can do a small improvement int the optimal code
    if nums[i]>0 then we can break the loop and return answer directly

  • @shubhamraj5184
    @shubhamraj5184 Před rokem

    I have watched many lectures of your but there are some lecture whose solution link is not in the description , As in this video itself please provide the link.

  • @user-xv7ms8bn2b
    @user-xv7ms8bn2b Před měsícem

    best explaination !!!

  • @user-if3ce9gm7p
    @user-if3ce9gm7p Před 7 dny

    Understood sir thank you soo much sir

  • @shubhamkumar170
    @shubhamkumar170 Před 9 měsíci

    Understood!! ❤❤

  • @ahmedyasser4928
    @ahmedyasser4928 Před 3 měsíci

    Understood ❤

  • @lakshmiprasanna7058
    @lakshmiprasanna7058 Před rokem

    Understood 💯💯💯

  • @bitran4283
    @bitran4283 Před 10 měsíci

    love it, thanks

  • @RohitRaj-kr7ti
    @RohitRaj-kr7ti Před rokem

    Hey @takeUforward
    While I was going through the optimal solution, ans.push_back(temp) will not eliminate duplicity. You will have to add in a set and then later use the set to derive ans as list.

    • @ujjwalkumarsingh5216
      @ujjwalkumarsingh5216 Před rokem +1

      nope, as we are using unique elements whenever sum gets to 0 through 2 while loops.

    • @RohitRaj-kr7ti
      @RohitRaj-kr7ti Před rokem

      @@ujjwalkumarsingh5216 Yeah noticed that.. its working fine..

  • @YourCodeVerse
    @YourCodeVerse Před 8 měsíci

    Understood✅🔥🔥

  • @manambalaji9547
    @manambalaji9547 Před 8 měsíci

    Excellent 👌

  • @secretvibz6300
    @secretvibz6300 Před 5 měsíci +1

    As Smooth as Butter 😃

  • @sakshiagrawal9106
    @sakshiagrawal9106 Před 3 měsíci

    thank you so much bhaiya❤

  • @parthtiwari8152
    @parthtiwari8152 Před 10 měsíci

    understood
    thanks striver

  • @rishav144
    @rishav144 Před rokem +4

    God of DSA❤

  • @RituSingh-ne1mk
    @RituSingh-ne1mk Před 6 měsíci +1

    Understood!

  • @Sumeet_100
    @Sumeet_100 Před 2 měsíci +1

    Thank you ❤

  • @placement123
    @placement123 Před 5 měsíci

    when implementing the second approach instead of using set, we can use unordered_map(with the second key as its index), and we will start i from 0 and j from i+1 and for the third value we can ensure by checking that the index of the last target element from the map should be greater than j :)

    • @lakshsinghania
      @lakshsinghania Před 2 měsíci

      hey, im not able to digest this thing in the 2nd approach
      arr is -1 0 1 2 -1 4
      and the i & j are pointing at -1 and -1 so arr[k] = -(-2) = 2 so for this we need to search in the entire array right
      and he stored [0 1 2] elements between -1 and -1
      but what if the arr was like this
      1 0 1 2 3 -4 and i is pointing to 1 and j pointing to 3 then arr[k] = -(4) = -4 then if we store [ 0 1 2 ] we will not find in the set as -4 is after the j pointer
      could u pls make me understand this as im bit confused

    • @CoDeEnthusiast-ev9zu
      @CoDeEnthusiast-ev9zu Před měsícem

      ​@@lakshsinghaniayou are right but there is a catch here ,
      When i is pointing to 1 and j is pointing to 3 we need to search for -4 in the hashset which is not available. However after that we will add the arr[j] into the hash set i.e. we will add the element 3 into hash set ..
      So in the next step j will point to 4 now we have to search for -(1-4) = 3 and this element 3 is present in the hashset thereby we will get the required unique triplet

  • @saketjaiswal9381
    @saketjaiswal9381 Před 11 měsíci

    thank us sir again

  • @her_soulmate
    @her_soulmate Před 10 měsíci

    Understood 🎉

  • @yashseth4626
    @yashseth4626 Před 6 měsíci

    can someone explain me ,, why we are redeclaring hashmap in every i ,,can not we make a one traversal and store all elements in the map at once .In last when we are inserting elements in a set after sorting ,can it will not avoid duplicacies?

  • @abhishekverma9946
    @abhishekverma9946 Před rokem

    Understood.🙂

  • @prashantshrivastav1334
    @prashantshrivastav1334 Před 3 měsíci

    Hello sir in two pointer approach when we got sum=0 why we are moving k to k-- since we can get different results with old i + new j + old k? 29:43

  • @anantsingh2004
    @anantsingh2004 Před rokem

    Understood😊