4 Sum Problem | Leetcode #18

Поделиться
HTML-код
  • Опубликовано: 7 сен 2024
  • This video explains a very important programming interview problem which is the 4 sum problem.This problem can be solved using multiple techniques and algorithms.I have explained all the approaches using simple examples.I have explained 3 techniques.The first one is just by using simple set which is the brute force approach.The second technique is by using set with 2 pointer technique. This is the best approach in terms of time complexity. The third approach is by using hashmap.This solution iis better than the naive approach.
    CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    ======================================PLEASE DONATE=============================
    🧡 SUPPORT OUR WORK: / techdose
    💚 UPI-ID: surya.kahar@ybl
    💞JOIN Membership: / @techdose4u
    ==============================================================================
    INSTAGRAM : / surya.pratap.k
    LinkedIn: / surya-pratap-kahar-47b...
    WEBSITE: techdose.co.in/
    TELEGRAM Channel LINK: t.me/codewithT...
    TELEGRAM Group LINK: t.me/joinchat/...
    =======================================================================
    USEFUL LINKS:
    🟠Must do TIPS to ACE Virtual Interview: • 🔴Must do Tips to ACE y...
    🟢Best strategy to excel your coding interview: • 🔴Best strategy to exce...
    🟡Get your dream job in 1 month: • 🔴Get your dream job in...
    🔵How to crack dream job in just 2 months: • How to crack dream job...
    🟣7 Days DSA plan: techdose.co.in...
    RELATED LINKS:
    Perfect subarray: • Perfect subarray | Goo...
    Subarray sum equals K: • Subarray sum equals K ...
    CODE LINK: techdose.co.in...

Комментарии • 115

  • @ayushdhiman8128
    @ayushdhiman8128 2 года назад +10

    first time ever saw the face of legend thank you for your tutorials !!

  • @zeta_meow_meow
    @zeta_meow_meow Год назад +2

    sir i like prefer these type of videos , as in from the rest of your videos that i saw , this one has your face , and i dont know why but these type of videos where i can see the instructors face , help me have better understanding

  • @NatureLover-oq6uc
    @NatureLover-oq6uc 2 года назад +1

    best explanation on youtube....Everyone on youtube just expalins brutforce approach but no one shows the code like you...HATS OFF

  • @spetsnaz_2
    @spetsnaz_2 3 года назад +5

    I might not have thought about the complexity of chained elements of hashmap in the interviews. Great!

  • @kellie9439
    @kellie9439 3 года назад +6

    you are amazing. thank you for the detailed explanation and clear thought and explanation process.

  • @kirtikedia6274
    @kirtikedia6274 5 месяцев назад

    2nd approach can be done without using set, which will make our time complexity O(n^3) instead of O(n^3)log(n) with this check
    while(start < end && arr[start] == arr[start+1]) start++;
    while(start < end && arr[end] == arr[end-1]) end--;
    This will make sure we don't check 2 sum for same values. Since array is sorted all same values will be adjacent.
    So skip the same values until we find new value
    Code -
    class Solution {
    public:
    vector fourSum(vector& arr, int target) {
    vector ans;
    int n = arr.size();
    if(n

  • @sathishkumar-dc9ce
    @sathishkumar-dc9ce 3 года назад +6

    i found that it can done in o(n^3) ....
    Loop through i and j and doing a two pointer approach

  • @AjayChetry
    @AjayChetry 2 года назад +3

    First, thanks for all the awesome videos. There could be another approach where it would take O(N^3) time if we first sort the array and then take O(N^2) two sums and iter over the original array to find K - ( i th two sum ) exist in the array and that should take O(N) time for each such operation. So the total complexity should be O(N^3)

  • @user-oy4kf5wr8l
    @user-oy4kf5wr8l 3 года назад +4

    Thank you so much buddy. Your video is really clear and very good explained... in details! thank you

  • @gauravsinha5830
    @gauravsinha5830 Год назад +1

    Thanks for taking the time to explain the ideas. However, the first continue optimization doesn't seem to be correct. It would not let the 4 pointers work in tandem. Anyway, the set will take care of the duplicates. I have yet to implement the 2 sum one.

  • @akshaykumarmalathkar2968
    @akshaykumarmalathkar2968 2 года назад +6

    In the second approach I think we don't need to use a set to handle the duplicates as we can simply compare the last added quadruple with the current one as you did in the 3rd approach.

  • @Gauravkr0071
    @Gauravkr0071 3 года назад +2

    in second approach , when sum= target u hv written, left=left+1, what if there is duplicate element in while loop also, how to check for dupliacte element in the innermost (while) loop

  • @TheBookOfRon
    @TheBookOfRon 2 года назад +4

    This is an amazing explanation. Thank you.

  • @sakshamsinghal5127
    @sakshamsinghal5127 3 года назад +1

    Really! Amazing video.....
    One more added in liked video.

  • @Mandeepsingh-jo5cf
    @Mandeepsingh-jo5cf 3 года назад +11

    Thank you sir.
    how much time it takes you to make a one video from code explanation to code writing?

  • @yatinarora1252
    @yatinarora1252 3 года назад +2

    Sir can you explain why we have kept i

    • @techdose4u
      @techdose4u  3 года назад +2

      No. Because a set of 4 elements should have unique indexed elements.

  • @dayserivera
    @dayserivera 2 года назад

    Thanks for the explanation!
    In my opinion the easiest one was the solution with hashtable.

  • @rechinraj111
    @rechinraj111 3 года назад +6

    Few days earlier same problem has been asked in DAILYHUNT. I couldn't solve😭

    • @techdose4u
      @techdose4u  3 года назад +1

      Ohhh....no problem. Maybe this will help in future.

  • @NAVEENKUMAR-uj7xe
    @NAVEENKUMAR-uj7xe 3 года назад +2

    Thank you Tech dose.

  • @AestroixCode
    @AestroixCode 3 года назад +1

    Lovely indeed ! thankyou sir for this.

  • @AsifIqbalR
    @AsifIqbalR 3 года назад +6

    Insertion in set is considered O(1) amortized, not O(log(n)).

    • @matrixtoogood5601
      @matrixtoogood5601 2 года назад

      In C++, you cannot insert a vector in the unordered_set without providing a hash function. Insertion in unordered_set is O(1) but insertion in set is O(logN)

  • @Sirajkhan789
    @Sirajkhan789 3 года назад +3

    great explanation !

  • @naveenchauhan1824
    @naveenchauhan1824 3 года назад +2

    Great explanation sir..thanks for the explanation.

  • @Wanderlust1342
    @Wanderlust1342 2 года назад +1

    love from USA

  • @muskan77639
    @muskan77639 3 года назад +1

    It will be nice if you could mention in which playlist you have a certain video in description of every video

  • @dayserivera
    @dayserivera 2 года назад

    Code translated to Java:
    public class Sum4 {

    public static List fourSum(int[] nums, int target) {
    List resultado = new ArrayList();
    int n = nums.length;
    if(n < 4)
    return resultado;
    Arrays.sort(nums);
    Map mapa = new HashMap();

    for(int i = 0; i < n - 1; i++) {
    for(int j = i + 1; j < n; j++) {
    List lista = new ArrayList();
    lista.add(new Pair(i, j));
    mapa.put(nums[i] + nums[j], lista);
    }
    }

    for(int i = 0; i < n - 1; i++) {
    if(i > 0 && nums[i] == nums[i-1]) continue;
    for(int j = i + 1; j < n; j++) {
    if(j > i + 1 && nums[j] == nums[j-1]) continue;
    int sum = target - nums[i] - nums[j];
    if(mapa.get(sum) != null) {
    for (Pair pair : mapa.get(sum)) {
    int k = pair.getIndex1();
    int l = pair.getIndex2();

    if(k > j) {
    if(!resultado.isEmpty() && resultadoContainsCurrentValues(resultado, nums[i], nums[j], nums[k], nums[l])) {
    continue;
    }
    List temp = new ArrayList();
    temp.add(nums[i]);
    temp.add(nums[j]);
    temp.add(nums[k]);
    temp.add(nums[l]);
    resultado.add(temp);
    }
    }
    }
    }
    }

    return resultado;
    }
    private static boolean resultadoContainsCurrentValues(List resultado, int iValue, int jValue, int kValue, int lValue) {
    for (List list : resultado) {
    if(list.get(0) == iValue && list.get(1) == jValue && list.get(2) == kValue && list.get(3) == lValue) {
    return true;
    }
    }
    return false;
    }
    public static void main(String[] args) {
    System.out.println(fourSum(new int[]{2,2,2,2,2}, 8));
    }

    static class Pair {
    int index1;
    int index2;
    public Pair(int index1, int index2) {
    super();
    this.index1 = index1;
    this.index2 = index2;
    }
    public int getIndex1() {
    return index1;
    }
    public void setIndex1(int index1) {
    this.index1 = index1;
    }
    public int getIndex2() {
    return index2;
    }
    public void setIndex2(int index2) {
    this.index2 = index2;
    }
    }
    }

  • @srihari_sh
    @srihari_sh 3 года назад +2

    Bro, Aren't you getting overflow error when u submit the code in leetcode if we go with method 2?

  • @sejalrai30
    @sejalrai30 2 года назад

    thank you so much

  • @mohammadruhulamin5991
    @mohammadruhulamin5991 Год назад

    awesome!!!!!!!!!!!!!!

  • @random2402
    @random2402 2 года назад +2

    Hello sir, your explanation is great. I want to know which software are you using to write on the screen. And also what is your set up, like are you using a tablet and writing on it using stylus or you are writing on the laptop using the mouse cursor?

  • @shreyamatade409
    @shreyamatade409 2 года назад +1

    Great explanation

  • @dogexploresworld1705
    @dogexploresworld1705 2 года назад

    Thank you!!! This was a great explanation!

  • @user-oy4kf5wr8l
    @user-oy4kf5wr8l 3 года назад +2

    A question plz. At 5:14, you said that the big O for set operation is O(lg N). is that true ?
    Time Complexity of HashSet Operations: The underlying data structure for HashSet is hashtable. So amortize (average or usual case) time complexity for add, remove and look-up (contains method) operation of HashSet takes O(1) time.
    For HashMap.containsKey(), it should be O(1) too. right ?

    • @techdose4u
      @techdose4u  3 года назад

      Avg is O(1) but WC is O(logN)

    • @techdose4u
      @techdose4u  3 года назад

      @@user-oy4kf5wr8l no need to make things complex. Just say O(1). If interviewer asks in detail then explain :)

    • @techdose4u
      @techdose4u  3 года назад

      @@user-oy4kf5wr8l I am not smart 😂

  • @RishavKumar-st9pi
    @RishavKumar-st9pi 2 года назад

    Pls read the leetcode problem carefully. Unique quadruplets doesn't mean unique i,j,k, and l. It means unique n[i], n[j], n[k], and n[l]. Your code is correct but you should have mentioned this way in explanation. Thanks for the answer though.

  • @ABHISHEKKUMAR-wc9ke
    @ABHISHEKKUMAR-wc9ke 2 года назад

    sec one was good

  • @naveenchauhan1824
    @naveenchauhan1824 3 года назад +1

    finally wait is over.

    • @techdose4u
      @techdose4u  3 года назад +2

      I am currently very busy so couldn't really post frequently. I will try to post atleast 1 per week.

  • @ashwanikumar4288
    @ashwanikumar4288 3 года назад +2

    How come insertion in set is LogN. Isn't it amortized O(1)?

  • @code_school6946
    @code_school6946 3 года назад +2

    Plz make this video for python as well

    • @ismail8973
      @ismail8973 3 года назад

      DSA Concepts are same whatever be the language doesn't matter.

  • @odongoemmanuel885
    @odongoemmanuel885 2 года назад

    why are you using n -4, n-3, n-2, n-1 where does the -4 come from

  • @chrisdahms9682
    @chrisdahms9682 2 года назад +1

    I love you! I love you!

  • @i_mchick5311
    @i_mchick5311 3 года назад +1

    Reminder ON :)

  • @mrniamster
    @mrniamster 2 года назад

    var sum = target - (arr[i] + arr[j]);

  • @MilindGupta
    @MilindGupta 3 года назад +1

    Sir there is 2 playlist of hash...
    One is hashing with 5 videos and one is with more than 10-15 videos...
    I have done this 5 video playlist so is the other playlist continuation of this playlist

    • @techdose4u
      @techdose4u  3 года назад

      No it's not. Other playlist has only problems. It's not a continuation, other videos are pending

  • @nikhilm4290
    @nikhilm4290 3 года назад +1

    Please explain some hard questions in leetcode

    • @techdose4u
      @techdose4u  3 года назад

      I am explaining topicwise. Whether hard or medium. It shall be done.

  • @premchandru05
    @premchandru05 3 года назад +1

    I would like to join your live course, could you please help me to register?

    • @techdose4u
      @techdose4u  3 года назад

      Yep. You can register when the forms are released.

  • @kirannagulakonda3443
    @kirannagulakonda3443 2 года назад

    can someone please suggest best way to implement hashing function for implementing 3rd approach in java as time complexity of custom HashSet depends on how best we can override the hashCode method

  • @chandragupta2828
    @chandragupta2828 3 года назад

    if make set at last in method 2 then time complexity will be O(n3 +nlogN)=O(n3) , am I right?

  • @sainathreddy2632
    @sainathreddy2632 3 года назад

    in method 2 if sum == tar why we are only moving only lefft++ , why not r++ or both can anyone explain

  • @xiangao1194
    @xiangao1194 3 года назад +2

    some questions about the complexities, for set insertion, hashset insertion should be constant time, isn't it? same constant time for get.
    The 3rd approach - generating all the two-sum takes n^2, plus looping through the sums, it's 2* n^2, may not be (n^2 * n ^2)

    • @techdose4u
      @techdose4u  3 года назад

      O(1) is amortized time, meaning average time. But worst case is not the same. For the 3rd approach, your chain length can go to N^2 and you might have to traverse the entire chain for each 2sum. Possible 2sums are N^2. So time is N^4.

    • @sachinthakan8211
      @sachinthakan8211 3 года назад

      @@techdose4u I think xian is right, even if we consider the worst-case we will find all two sums for a single pair (i, j), and the rest of the pairs will do nothing. So we will traverse all N2 pairs and in the worst case, we will end up including all two sums from the map to our answer. So-net operations are the sum of all operations needed to fetch two sums from the map, which is still O(N^2)
      EDIT: though making map initially can take O(N^4) in worst case

  • @mohammadarif7284
    @mohammadarif7284 2 года назад

    This an amazing explanation.
    How can i contract with you brother?

  • @swappy4515
    @swappy4515 3 года назад

    Second approach 5:27

  • @Abhishek-qw2xt
    @Abhishek-qw2xt 2 года назад

    Thank you so much for such wonderful videos, these videos have helped me learn so much in so little time!

  • @hapysethi1306
    @hapysethi1306 3 года назад +1

    Please explain how the 3 approach takes n^4, I think it takes n^3

    • @techdose4u
      @techdose4u  3 года назад +1

      If chain length is N^2 and (Target-2sum) = 2sum then you will get N^4.

  • @surendarraj715
    @surendarraj715 3 года назад

    I am getting signed integer overflow bro for the sum value

  • @abhinavreddy5350
    @abhinavreddy5350 3 года назад +2

    tq anna

  • @zod1ack_csgo_clips425
    @zod1ack_csgo_clips425 3 года назад +1

    Nice

  • @LegitGamer2345
    @LegitGamer2345 3 года назад

    please solve Water Connection Problem on gfg

  • @VishalSharma-hq5ti
    @VishalSharma-hq5ti 3 года назад +1

    I guess, Approach 3 will fail in case all elements are same?

    • @ismail8973
      @ismail8973 3 года назад

      No it will work even if all elements are same. But this is worst case situation and the time complexity will become O(N^4)

  • @shivanshgupta4342
    @shivanshgupta4342 2 года назад

    i am getting runtime error: signed integer overflow:
    in this line sum=nums[i]+nums[j]+nums[left]+nums[right];

    • @MantuKumar-xu3nf
      @MantuKumar-xu3nf 2 года назад

      Define long long int sum,sum1,sum2; instead of int sum and sum1=nums[i]+nums[j];
      sum2=nums[left]+nums[right];
      sum=sum1+sum2;
      It will not give you any error

  • @neerajpandey7273
    @neerajpandey7273 3 года назад +1

    excellent :)

  • @330_atharvashirgave8
    @330_atharvashirgave8 2 года назад

    Your first code is not running

  • @abhishekshetty9138
    @abhishekshetty9138 3 года назад +1

    sir this can be even done through backtracking ryt ❔

  • @atifkhan-ix1jc
    @atifkhan-ix1jc 3 года назад +1

    I change speed from 2x to normal I was not able to identify his voice

  • @atharvakulkarni2024
    @atharvakulkarni2024 3 года назад

    BTW MOST OPTIMAL SOLUTION USES NO DATA STRUCTURE
    ONLY 2 POINTERS

  • @madhavanr8996
    @madhavanr8996 3 года назад +1

    👌👌

  • @deeptarkoroy6724
    @deeptarkoroy6724 3 года назад

    I have done using the second algorithm.But my set is containing duplicate vectors.How is this possible xD

  • @unknownurs2367
    @unknownurs2367 3 года назад

    Coool

  • @TheMsnitish
    @TheMsnitish 3 года назад

    link to buy the mic ?