L11. Subset Sum II | Leetcode | Recursion

Sdílet
Vložit
  • čas přidán 2. 03. 2021
  • Check our Website:
    In case you are thinking to buy courses, please check below:
    Link to get 20% additional Discount at Coding Ninjas: bit.ly/3wE5aHx
    Code "takeuforward" for 15% off at GFG: practice.geeksforgeeks.org/co...
    Code "takeuforward" for 20% off on sys-design: get.interviewready.io?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/invite/xexnpc4u
    Take 750 rs free Amazon Stock from me: indmoney.onelink.me/RmHC/idje...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v3cO/8hu879t0
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    ---------------------------------------------------------------------------------------------------------------------------------------------------- I have decided to make a free placement series comprising of video lectures(C++ and Java) on the entire SDE sheet.. ✅(bit.ly/takeUforward_SDE)
    ✅Entire Series: bit.ly/placementSeries
    ✅Problem Link: leetcode.com/problems/subsets...
    C++/Java Code: takeuforward.org/data-structu...
    Want to become an advanced level programmer in a structured way? Join the "Ascend" batch starting on 4th March and begin your journey to the advanced level.
    Intermediate to Expert Level Coder in 10 Months (Batch preview available): unacademy.com/batch/ascend-in...
    Use Code "TAKEUFORWARD" to unlock all the free classes and 10% discount on the Subscription
    Get access to all the free lectures: unacademy.cc/daily_learning
    ✅This is where I teach: ----- Use coupon-code "TAKEUFORWARD" for getting 10% on my course at GFG: bit.ly/striver_cpCourse
    ✅Use coupon-code "TAKEUFORWARD" for getting 10% for all GFG courses: bit.ly/tuf_gfgCourse
    If you appreciate the channel's work, you can join the family: bit.ly/joinFamily
    Thumbnail Creator: / rikonakhuli
    ✅ Striver's Linkedin Profile: / rajarvp
    ✅ Instagram: / striver_79
    Connect with us: t.me/Competitive_Programming_tuf (Use Link in Mobile only, if not works search "takeUforward" in telegram)..
    #dsa #leetcode #placements

Komentáře • 362

  • @Vishalraj_1
    @Vishalraj_1 Před 2 lety +383

    most of the time, I have solved questions by myself. But then also I watch your videos, Two reasons behind this is most of the time, I get to know more approaches to solve the question. and the second thing is how I can tell the solution to the interviewer. Yesterday was my interview and I tell brute then optimal approach with intuition(like you). And the interviewer was happy with my presentation. Thanks you making videos, it help me in both problem solving + presentation skills.

    • @akmansr7149
      @akmansr7149 Před 2 lety +11

      Hi, I am still unable to solve problems on my own. what should I do? 😥😥

    • @omprakashhardaha7736
      @omprakashhardaha7736 Před 2 lety +12

      @@akmansr7149 practice

    • @akmansr7149
      @akmansr7149 Před 2 lety +10

      @@omprakashhardaha7736 bhai doing that since a very long time. Seems like i suck. I can't solve problems without looking at discussion section or yt videos 😭

    • @omprakashhardaha7736
      @omprakashhardaha7736 Před 2 lety +7

      @@akmansr7149 bro i hv also same problem
      I suggest follow DSA kunal kushwaha course. You can start from recursion or binary search video.

    • @shivansh2870
      @shivansh2870 Před 2 lety +3

      @@akmansr7149same problem

  • @CSBBADRIGAUTAM
    @CSBBADRIGAUTAM Před rokem +118

    A huge thanks to you bro. This question helped get into job
    In my technical interview, I was to rate my coding skills and I said 8.
    He was supposed to ask the question of finding subsets of fixed size, and since I said my rating would be 8, he changed question to finding all subsets.
    I explained the code and everything. He was not believing my algo was correct. I guess What my interviewer was thinking to modify the original algo for prev question or something. He was saying I was wrong and I got worried a lot.😟😟
    Then I shared my screen and drew the tree and explained everything as you did in this video (not as good as you though 😅😅) and he was *completely convinced* . He told me to move onto another question and he was still doubtful on the 1st question and did some research while I am doing my 2nd question (which is different question but same recursion application) and told me the solution for the first was the best optimal approach and got impressed a lot. 😂😂
    A huge thanks to you bro.

    • @abc-ym4zs
      @abc-ym4zs Před rokem +4

      in which software u have explained tree to the interviewer can u please tell if I encounter these type of persons it will be useful

    • @CSBBADRIGAUTAM
      @CSBBADRIGAUTAM Před rokem +4

      @@abc-ym4zs I didn't use any software, I just opened a document and explained using "/" and "\" as the links, wrting in next lines for children nodes or slashes (/ and \) and numbers in place of nodes. I used my mouse to show how each recursion goes for. It was online interview

    • @akashsingh2722
      @akashsingh2722 Před rokem +1

      Damn!! congrats bhai

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

      I was also asked this question once in an interview and I told the interviewer that we can solve this using recursion then he changed the question 😂😂

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

      ​@@nimeshpareek953 what was the point of changing the question ? Are you not supposed to know the answer to what they ask lol Also what was the new question

  • @codingwithsmallsteps2878
    @codingwithsmallsteps2878 Před 3 lety +35

    Hi Striver. Thank you for the wonderful explanation of the Subsets II leetcode problem. I read the codes in discuss part for the problem but was unable to understand the logic behind it. But after watching your video, I have understood the logic and can write code for it.

  • @-EE-AKASHJHA
    @-EE-AKASHJHA Před 2 lety +65

    I have just solved 5 medium questions of leetcode having 10000+ likes in such a way that they don't feel even like easy problems, and when I used to see those questions earlier, I got fear and a question about whether I will be able to solve these questions ever but now I have not only solved them but understood the logic as well as written the pseudo code and also drawn the recursion tree.
    THANK YOU SO MUCH RAJ BHAIYA...

    • @diyapathak2413
      @diyapathak2413 Před rokem +6

      pls tell me how b/c i feel so scared looking at them rn

    • @RishabhSingh-xn3xu
      @RishabhSingh-xn3xu Před 11 měsíci +3

      Everyone is Pro Until the new Question drops in the interview

  • @takeUforward
    @takeUforward  Před 3 lety +7

    Please leave a small comment if you understand by spending your time here, every comment motivates me more :)
    C++ Code: github.com/striver79/SDESheet/blob/main/Subset-II_Cpp
    Java Code: github.com/striver79/SDESheet/blob/main/Subset-II_Java
    Instagram(For live sessions): instagram.com/striver_79/​

    • @yuvrajluhach5665
      @yuvrajluhach5665 Před 2 lety

      For Java code github link you have given C++ code , must be a mistake . 👍 Loving this series . I'm a 3rd year student any words of wisdom?😀
      Like what should I not neglect whatever happens.

    • @sheturaj7437
      @sheturaj7437 Před 2 lety

      One thing I did not understand is that aren't we generating wrong subsets if we are sorting the input array? For example:- if arr = [2,3,1,3,2], which after sorting would become [1,2,2,3,3], then won't [1,3,3] (and many more) which would be generated by your logic would be wrong since [3,1,3] would be the right subset?

  • @anshumanpanigrahi7817
    @anshumanpanigrahi7817 Před 3 lety +10

    I was having a doubt in this question, and I searched it on CZcams. Surprisingly, you solved this question before and I was delighted to know it from you.

  • @rishabhkukreja6910
    @rishabhkukreja6910 Před 3 lety +14

    Thanks a lot for the videos
    You are doing a great job
    Sometimes even if i have done the question before i still watch your video and i learn new ways to approach the same problem
    Great work !! Keep going !

  • @adityarallapalli8308
    @adityarallapalli8308 Před 9 měsíci +5

    i != idx,
    instead of above condition,
    we can also write i > idx,
    which is intuitive.

  • @aakritisingh399
    @aakritisingh399 Před 2 lety +21

    Indeed a great explanation, this problem has similarities to the combination sum-II problem. Enjoying the recursion series.

  • @AdityaKumar-be7hx
    @AdityaKumar-be7hx Před rokem +2

    understood! The problem as well as the fact that I don't need to follow any one else for my algorithmic preparation. Keep up the great work!

  • @jeremysilwoman
    @jeremysilwoman Před 2 lety +2

    another easy way i feel is using bits. say we have one 1, two 2 and one 3. So we can choose either one or zero 1s, two or one or zero 2s and one or zero 3s. so we can have an array to store count of each element. we start with {}. now we can either use one 1s or zero 1s. So {}, {1}. Now we can use zero/one/two 2s. So we have 2, 22, 222, 12, 122, 1222, 1, {}.similarly for next element.

  • @atharvakalele37
    @atharvakalele37 Před 2 lety +2

    the best channel for competitive programming! thanks a lot brother!

  • @rohitsai9010
    @rohitsai9010 Před rokem +2

    Fantastic explanation.. U made recursion more easy and interesting.. Hats off your to patience

  • @pulkitjain5159
    @pulkitjain5159 Před 2 lety +9

    following this series made so easy to do these problems of Subset1 and SubsetII as these follow the same concept of combination1 and Combination2 ,it is improving very much concepts of Recursion ,thanks for the awesome playlist sir

  • @mukuldaftary9230
    @mukuldaftary9230 Před 3 lety +1

    Very Very Good Explanation , Very Helpful , keep on making these kind of videos.

  • @aratrik247
    @aratrik247 Před 2 lety +7

    Watched ur previous videos on recursion and coded this one by myself....I am amazed I can finally solve recursion problems....
    Thanks bhaiya for ur wonderful explanations😃

    • @vedangfate6290
      @vedangfate6290 Před rokem +1

      Same here bro. The way he has simplified the whole process is so amazing

  • @akshitmangotra5370
    @akshitmangotra5370 Před rokem +2

    Thanks man! You make it so so so easy!

  • @yuvrajluhach5665
    @yuvrajluhach5665 Před 2 lety +23

    Combination II helped with this one , coded solution without referring video solution👍 developing the intuition

  • @anmolagarwal5600
    @anmolagarwal5600 Před rokem +1

    Alternative: when ignoring current element, also ignore all elements similar to current element.
    void help(vector& nums, int i, vector& s, vector temp){
    if(i == nums.size()){
    s.push_back(temp);
    return;
    }
    int j = i;
    while(j

  • @joydeb8202
    @joydeb8202 Před 3 lety +5

    Thanks a lot bhaiya...
    Abhi apka CP sheet kar raha...
    SDE Sheet iske baad🙌
    Sukriya for all this help.❤️❤️

  • @bhaveshkumar6842
    @bhaveshkumar6842 Před 2 lety +2

    This is the best placement series!!!!

  • @ranasauravsingh
    @ranasauravsingh Před 2 lety +1

    UNDERSTOOD... !!!
    Thanks striver for the video... :)

  • @rupamdwivedi9463
    @rupamdwivedi9463 Před rokem

    THANK U SOOOO MUCH FOR WONDERFUL EXPLANATION

  • @Munchen888
    @Munchen888 Před 6 dny

    24:55
    Can we use a condition “if i > idx …”
    It would be the same as in previous videos. Thus we don’t take the element we had seen.

  • @Shivam-Varshney
    @Shivam-Varshney Před 6 měsíci +2

    7:29.5 is important for understanding the indexing of the f(5,{3}) they took 5 as you have moved from 4th to the 5th index of this stuff .

  • @tanmaysatsangi131
    @tanmaysatsangi131 Před 2 lety +3

    plz anyone explain why the complexity of O(nlogn) to inset into set. OR I missed something at 2:22.
    Thanks in advance

  • @Lalit_Shirsath
    @Lalit_Shirsath Před 3 lety +4

    for reducing time complexity ....can we use unordered set ?
    because all operations like insert will be O(1) ........ can we do that

  • @parthsalat
    @parthsalat Před 2 lety +2

    Thanks for the amazing explanation!

  • @Shivam-Varshney
    @Shivam-Varshney Před 6 měsíci +2

    25:02 if I!=Ind && nums[I] == num[i-1] continue and don't pick these conditions
    It means your I should be equal to index to be picked up in the call and if 2 successive indexes of array are same then don't pick up them in recursion call 🤙😎

  • @iWontFakeIt
    @iWontFakeIt Před 2 lety +3

    ooooh! man, i solved this problem at first but i was wondering what went wrong as this problem is similar to combination sum problem, but finally i realised that i need to add all subsets into the final array. Hence i solved the problem and successfully understood the subtle difference between these two problems.

    • @av21015
      @av21015 Před rokem

      Yeah me too faced the same issue . I didn't think there is no base case required.

    • @shreyxnsh.14
      @shreyxnsh.14 Před 2 měsíci

      @@av21015 yeah, i was returning for the base case, thats why it wasnt working

  • @ShubhamKumar-km8pm
    @ShubhamKumar-km8pm Před rokem

    Thanks striver sir for explaning it the best way possible💯💯

  • @aaryankedia3919
    @aaryankedia3919 Před rokem

    Hey! Thank you such a clear explanation. I had a doubt, for the time complexity(TC), wont we add the time required for sorting the list?

  • @user-ti3bd8mp1w
    @user-ti3bd8mp1w Před rokem

    understood
    Thank you striver for such an amazing explanation..

  • @amitghosh4548
    @amitghosh4548 Před 3 lety

    I didn't understand the space complexity. Why it will take extra O(K) [k is average length] won't it take O(2^n) + O(K) ? I guess a single ds is used to store and remove subsets.... Please someone explain if I m wrong 🤐

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

    able to solve this without seeing ur video!! cheers to your teaching method

  • @sankalpjain4841
    @sankalpjain4841 Před 3 lety +1

    Well Explained, Thanks ❤️

  • @dennyage4791
    @dennyage4791 Před 2 lety +3

    but how' s the time complexity of converting hashset to List is ml* logm ?

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

    Efficient solution said by you is having the same time complexity as of brute force becuase in brute force it is going to take O(2^nlog2^n) and logbase2 to 2^n will be n so 2^n*n so what is the difference in time complexity between brute and efficient they are same.

  • @SDE-wq4tl
    @SDE-wq4tl Před 2 lety +1

    how the power set of [4,4,4,1,4] will include set [1,4,4] and they did not ask to sort the array and then get power set?

  • @wisdomkhan
    @wisdomkhan Před 2 lety

    this question is less of recursion but more in optimising the input and output

  • @AlbertoRodriguez-oe6jo
    @AlbertoRodriguez-oe6jo Před 2 lety +7

    This is a backtracking problem, I mean recursion + backtracking, I thought I was missing something in the explanation but recognized it when I looked at the code.

  • @mohdkhaleeq7468
    @mohdkhaleeq7468 Před 2 lety

    in time complexity 2^n log 2^n is also added for sorting?

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

    Thanks for the awesome explanation Striver. Can anyone help me understand why we are not using the pick and not-pick approach for the combination sum2 and subset sum2 problems? Didnt completely understand the reason for the differences in the approaches chosen.

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

    hi man, thankyou for making video for us even if your not able to speak loud after tumor operation. ❤
    love you bhaiya

  • @rishikas8276
    @rishikas8276 Před rokem +3

    I was trying to solve questions but for topics like recursion ,backtracking , graphs and stuff I’m not able to arrive at the solutions by myself ..I’m ending up referring to the solutions for most of questions like combinations , printing permutations etc
    Can you please tell me how to go about it so that I can come up with the solutions myself or if I’m doing something wrong
    Thanks!

    • @kunal4710
      @kunal4710 Před rokem

      ALWAYS TRY TO DRAW RECURSION TREE OF WHATEVER CODE COMES TO YOUR MIND THEN ONLY YOU WILL GET TO KNOW WHERE YOU ARE WRONG

  • @HiteshWadhwani8
    @HiteshWadhwani8 Před 3 lety

    whats the link to previous video, not able to find it

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

    Beautifully Explained!

  • @shanthiyasekar7317
    @shanthiyasekar7317 Před rokem +1

    can anyone tell me what is the difference between combination sum problem and subset sum i feel both are same, i am not able to find the difference

  • @TheNishant30
    @TheNishant30 Před rokem +3

    this can also be solved with a modified take/not-take approach. it's just that when you are not taking an element, you dont only skip the current element, but also skip all its duplicates as well. essentially, you modify the recursive case to look for the next unique element.
    here's a pseudocode
    //BASE CASE
    if index > nums.length
    => push temp array's copy to result array
    => return
    //RECURSIVE CASE
    //all subsets that'll contain an element at a particular index
    => push nums[index] to the temp array
    =>call the function on (index+1)
    //all subsets that will NOT have an element at that particular index AND WILL NOT HAVE ITS DUPLICATES EITHER
    => pop the last element off your temp array
    => look for the next UNIQUE ELEMENT and call the function on that unique element's index.
    // here you dont only skip the element at index, but also index+1 if it's a duplicate, index+2 if it's also a duplicate..... so on and so forth, until you find the next unique element in the array. once you do, you call the function on that index. but what happens when there's no next unique element [1, 2, 2]? when you exclude 2 and look for the next UNIQUE element, will you find it? NO. what will you do then? not make a recursive call AT ALL? how will you reach the leaf node then? the base condition for that branch will not get satisfied and you will skip combinations that should have been there. HINT: IF THERE IS NO "NEXT" UNIQUE ELEMENT, CALL THE FUNCTION ON THE LAST DUPLICATE.
    let i = index+1
    for(i; i < nums.length; i++) //Javascript folks, just use a var declaration here (-_-)
    {
    if (nums[i] == nums[index]){
    continue;
    }
    else {
    break;
    }
    }
    => call the function and pass i as index for that call.

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

    simple as that, if array does not contains duplicates use pick and non pick method , if it has duplicate use for loop method :)

  • @atharvakulkarni2024
    @atharvakulkarni2024 Před 3 lety +1

    I have a question? How would this recursion stop if theres no base case unable to understand?

    • @takeUforward
      @takeUforward  Před 3 lety +9

      Because the for loop will not get executed and hence no further recursion calls will be made

  • @abhimanyu6534
    @abhimanyu6534 Před 3 lety +39

    Great explanation
    But I think SDE sheet is getting difficult now 🥺😬😬

    • @tekken1935
      @tekken1935 Před 3 lety +1

      Did u finish?. How is placement going?

    • @abhayj8706
      @abhayj8706 Před 3 lety +12

      @@tekken1935 i am in first year
      I am on dp

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

      Been 2 years how you doing

  • @venkatakasinathpeesapati3146

    Striver You are really Amazing..!

  • @Rajat_maurya
    @Rajat_maurya Před 2 lety +3

    void f(vector &v1,vector &ans,vector &ds,int i)
    {
    ans.push_back(ds);
    for(int j=i;j

  • @_aka5h
    @_aka5h Před rokem

    Isn't the time complexity O( n * 2^n ) since we are pushing a vector every time recursive function is called.

  • @hh8xking30
    @hh8xking30 Před 2 lety +1

    Hi Striver, if we are not returning from recursive call then, all those recursive call will be stored only in memory. So, should not we had to return them ...?

    • @curiossoul
      @curiossoul Před rokem

      recursive call either return or end up filling the call stack and result in stack overflow. You can imagine recursive stack as normal Stack data structure with finite memory slots. If terminating condition is not added, it will blow up.

  • @parthsalat
    @parthsalat Před 2 lety +15

    C++ code starts at 25:30

  • @nallapusrikar8490
    @nallapusrikar8490 Před rokem

    I have a small doubt in line 4 -"ansList.add(new ArrayList(ds))", The ds is already an object of type ArrayList then we again create an object of type ArrayList by sending the parameter. why are we doing it?

    • @hx-ql3de
      @hx-ql3de Před 7 měsíci

      to avoid reference sharing

  • @DIVYANSHMISHRA08
    @DIVYANSHMISHRA08 Před 3 lety +1

    from index we have to search (all combination)till last element hence func(i+1,...) in this instead of index+1?

  • @035asadali8
    @035asadali8 Před 2 lety +1

    bruh i dont know how i am solving all these question using recursion , i mean i am not thinking anything just write code and its work and when i draw tree or something i got confused ,anyone tell me what should i do

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

    Hey Striver, Why do you use For loop in some solutions while not in others? When do we go for the For loop. I understand that this is just reducing effort of picking the element one at a time. Please let me know if i am wrong.

  • @vaibhavsingh1282
    @vaibhavsingh1282 Před rokem

    asking from the people who have cracked these interviews do u actually tell the interviewer the brute force and optimal approach of every problem or we can just tell them one approch

  • @sarthak1317
    @sarthak1317 Před 3 lety +3

    In the brute force solution do we have to sort the subarray before putting it into a set ? if no can someone tell me how can we store unique lists in hash set, like {1,2} and {2,1} won't be added twice. Thanks in advance

    • @prabhat2342
      @prabhat2342 Před 3 lety +1

      Yes, u will have to sort the elements of list before inserting it in the hash set. Then only set will be able to remove the duplicates, otherwise {1, 2} and {2, 1} will be treated as different subsets.

    • @sarthak1317
      @sarthak1317 Před 3 lety

      @@prabhat2342 thank you for clearing that out. I have another question, hash set store the address of these objects as key right? So won't {1,2} and {1,2} will be treated as 2 unique objects? I'm sure I'm wrong about something. Please enlighten me.

    • @prabhat2342
      @prabhat2342 Před 3 lety +1

      @@sarthak1317 no doubt that both the addresses are unique. But the task of hashset is to remove the duplicates. So if {1, 2} is already present in the set and u want to insert another {1, 2} (having different address) then only one of two will be kept in the set, the other will be removed.

    • @sarthak1317
      @sarthak1317 Před 3 lety +1

      @@prabhat2342 understood, thank you for clearing it out, Basically hashSet takes care of duplicates with same addresses, and stores only unique structures. Thank you again😊

  • @antrapurohit8010
    @antrapurohit8010 Před 2 lety

    I have one query if anyone can comment:
    in java solution, Line 4, why there is a need to create new ArrayList from ds? Cant we add ds directly to ansList

  • @codemachine7381
    @codemachine7381 Před 2 lety

    Absolute masterclass...

  • @ayushpatel4475
    @ayushpatel4475 Před rokem

    Anybody can help me what is the difference between index and i in this qtn?

  • @anuragdas7608
    @anuragdas7608 Před rokem

    hey Striver why didn't you did i>ind similar to the one you did in combination sum II video as they are quite similar in terms of conditions having unique solution sets ?
    Also the question states that return the solution in any order so it doesn't matter if you sort the array or not as it would increase the time complexity :)

    • @kunal4710
      @kunal4710 Před rokem

      IF U WANT U CAN DO i>ind IT WILL BE SAME AS WE HAVE TO MAKE SURE THAT WE PICK 1ST ELEMENT AND AFTER THAT WE CAN SKIP ELEMENTS
      ALSO IF U WANT TO SKIP DUPLICATES WITHOUT TAKING SET YOU HAVE TO SORT IT THEN ONLY DUPLICATE ELEMENTS WIIL BE TOGETHER AND YOU CAN SKIP IT BY COMPARING IT TO PREVIOUS NUMBER

  • @ALLIN-dc5my
    @ALLIN-dc5my Před 7 měsíci

    can anyyyyyyyyyone explain how can i!=ind will even satisfy this cond cause it says int i = index in starting of for loop and casue of recursion for loop starts again and again making i == increased index so how can they not be equal in any case. Pleaseeeeeeeeeeee explain anyone.

  • @neilmaheshwari9600
    @neilmaheshwari9600 Před 2 lety +2

    Striver(bhaiya) i can't say aapki videos kitni helpful hai bs itna kahunga maine 5 6 alag alag logon ke recursion videos dekhe kabhi concept itna clear ni hua jitna aapse hua hai its a humble request aise hi guide karte rahiye and DP ki bhi series nikal dijiye...

  • @rohandevaki4349
    @rohandevaki4349 Před rokem

    isnt the time complexity n*n ? the first n is for visiting each element once and then reiterating it from 0 to n? how is it 2^n *n ?

  • @praveenkumarshah8581
    @praveenkumarshah8581 Před 3 lety +2

    please use light color ink on dark background...

  • @vasanthanv6143
    @vasanthanv6143 Před rokem

    We are sorting the array, right? Why the time complexity for sorting the array is not taken into account? I know sorting is much better than storing the result into set and then converting into array List, but Arrays.sort() itself has some time complexity, right? Correct me if I am wrong.

    • @akashfern377
      @akashfern377 Před rokem

      total elements in nums are less then 10 as given in the constrains, so sorting 10 elements would not take much time

  • @rohandevaki4349
    @rohandevaki4349 Před rokem

    even the powerset method with bit manipulation without recursion works here, which time complexity is 2^n * n

  • @venkateshvenky2880
    @venkateshvenky2880 Před rokem +1

    Understood clearly.

  • @GauravSharma-ij1ym
    @GauravSharma-ij1ym Před 4 měsíci

    Bruteforce approach TC should be 2^n * k*Logm where k is average sizE of subset and m(~2^n) is no. Of elements in the set . Why did u take 2^n * m*Logm. Subset size will not be 2^n. Can anyone explain?

  • @aasthagoyal5059
    @aasthagoyal5059 Před 2 lety +1

    Why are we removing elements during backtracking .In explanation I don't find any point where I should remove element.Can anyone explain the reason?

    • @abhishekc3556
      @abhishekc3556 Před rokem

      you should draw the recursive tree and trace the recursion and you'll understand that there are some areas where you'll have to pop of the last element.

  • @rohandevaki4349
    @rohandevaki4349 Před rokem

    pick and not pick is working with arralist contains method ,its time complexity is O(K), so total time complexity is (2*N *k),where k is the number of combinations

    • @kunal4710
      @kunal4710 Před rokem

      //NOT OPTIMAL APPROACH AS WE ARE USING EXTRA SPACE AS SET FOR STORING ELEMENTS

      void solve(int i,vector& nums,vector temp,set< vector > &s){

      if(i==nums.size()){

      sort(temp.begin(),temp.end());
      s.insert(temp);
      return;
      }

      //include
      temp.push_back(nums[i]);
      solve(i+1,nums,temp,s);
      temp.pop_back();

      //Exclude
      solve(i+1,nums,temp,s);



      }

      vector subsetsWithDup(vector& nums) {

      vector ans;
      set< vector > s;
      vector temp;

      solve(0,nums,temp,s);

      for(auto it=s.begin();it!=s.end();it++){

      ans.push_back(* it);
      }

      return ans;
      }
      SEE IT WORKS BUT IN THIS CASE YOU HAVE TO USE EXTRA SPACE HENCE NOT OPTIMAL

  • @linhinNTU
    @linhinNTU Před rokem

    i dont get it why the index of [1,2] is 2 in the video, can anyone explain for me?

    • @wsniper-dark154
      @wsniper-dark154 Před rokem

      I think we are passing the "current subset" and "index for the next operation" in the function.
      So, since we alr took 2 in last operation, which is at 1 index now we must give the current index + 1 i.e. index 2.

  • @nahidfaraji5069
    @nahidfaraji5069 Před rokem

    Can anyone help me out, with exactly how the recursion calls working inside this for loop? I can't draw the recursion tree for this.

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

      same problem code is tottaly different from tree

  • @nikeshmali8506
    @nikeshmali8506 Před 3 lety

    wow, thank you!

  • @lostcyrus8578
    @lostcyrus8578 Před rokem

    stll cant understand why you did i!=ind these both are same or not?

  • @amarjeetkumar-hk2jl
    @amarjeetkumar-hk2jl Před rokem

    @takeUForwad can can recursive code be written without base case? Please explain this.

  • @satyampande684
    @satyampande684 Před 2 lety

    understood!!

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

    I tried this appproach but i am getting repetitive sub_sets, how can i improve this.

  • @yashreddy7554
    @yashreddy7554 Před 3 měsíci +1

    Can anyone help why there is no base case for the recursion

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

      Our base case would have been:
      if index == len(arr):
      return
      but here, there is a for loop in the code that only goes till the last index, so index wont go beyond the length of the array, so no need for that base case

  • @bhargav1811
    @bhargav1811 Před rokem

    I am facing problem in test case = [4,4,4,1,4]
    Expected output - [[],[1],[1,4],[1,4,4],[1,4,4,4],[1,4,4,4,4],[4],[4,4],[4,4,4],[4,4,4,4]]
    My output- [[4],[4,4],[4,4,4],[4,4,4,1],[4,4,4,1,4],[4,4,4,4],[4,4,1],[4,4,1,4],[4,4,4],[4,1],[4,1,4],[4,4],[1],[1,4],[4],[]]
    My python code is -
    class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
    answer = []
    def solve(index, l):
    answer.append(l[:])
    for i in range(index, len(nums)):
    if i != index and nums[i] == nums[i - 1]:
    continue
    l.append(nums[i])
    solve(i + 1, l)
    l.pop()
    solve(0, [])
    return answer

  • @nishanttiwari9736
    @nishanttiwari9736 Před 2 lety

    I have a doubt!! What if we remove the duplicates from nums array in the beginning itself

    • @smrutisouravsahoo972
      @smrutisouravsahoo972 Před rokem

      You will get wrong answers because while returning subset [2,2] is an answer which wont show up if you remove the duplicates at the early stage.

  • @SatyamKumar-bw4vi
    @SatyamKumar-bw4vi Před 2 lety +1

    Hare Krishna! Great!

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

    Why there is no base case in this recursion ?

  • @user-cs2us9jr7e
    @user-cs2us9jr7e Před 3 měsíci

    00:00 Solve subset sum2 problem with no duplicate subsets
    04:06 Access all courses and get a free certification exam with subscription
    08:25 Generating all unique size 2 lists from a given list.
    12:16 Generate all sublists of given list
    15:55 Generating unique subsets with recursion
    19:42 Time and space complexity of recursive function
    23:19 Generate subsets of a given array
    26:51 Explanation of recursive code with data structure

  • @nikunjgarg3754
    @nikunjgarg3754 Před 2 lety

    for brute force, i wrote this:
    class Solution {
    public:
    void uniqueSubsetHelper(int index, int n, vector &arr, set &ans, vector &temp) {
    if (index == n) {
    sort(temp.begin(), temp.end());
    ans.insert(temp);
    return;
    }
    // pick
    temp.push_back(arr[index]);
    uniqueSubsetHelper(index+1, n, arr, ans, temp);
    // don't pick
    temp.pop_back();
    uniqueSubsetHelper(index+1, n, arr, ans, temp);
    }
    vector subsetsWithDup(vector& nums) {
    set ans;
    vector temp;
    uniqueSubsetHelper(0, nums.size(), nums, ans, temp);
    vector finalAns;
    for (auto it = ans.begin(); it != ans.end(); it++) {
    finalAns.push_back( * it);
    }
    return finalAns;
    }
    };
    but it isn't giving correct ans. Please help me someone.

    • @abhishikthraj6921
      @abhishikthraj6921 Před 2 lety +1

      i think you are just using two recursive calls while there can be n of them
      so try using a loop as he explained

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

    yooo! i was able to solve it on my own

  • @vishvkakadiya5014
    @vishvkakadiya5014 Před 3 lety +1

    Nice Explanation!

  • @anubhavkalia5130
    @anubhavkalia5130 Před 3 lety +1

    Thanks Bhaiya

  • @prabhakaran5542
    @prabhakaran5542 Před 28 dny +2

    Understood ❤

  • @adarshjaiswal7334
    @adarshjaiswal7334 Před rokem

    What's the purpose of making deep copy here? How actually it required?

  • @adityachava9803
    @adityachava9803 Před rokem

    Hi striver,
    why we dont add the base condition in this problem ?
    i.e if (index == nums.length - 1) ?

    • @amitrawat8879
      @amitrawat8879 Před rokem

      same doubt

    • @tasneemayham974
      @tasneemayham974 Před rokem

      Because the for loop is going to end the recursion. Look, the purpose of the base case is to end the recursion. Suppose we are at index 5 and the loop runs till i

  • @parthsalat
    @parthsalat Před 2 lety +1

    Complexity analysis at 20:30

  • @jayadubey_22
    @jayadubey_22 Před 3 lety +2

    Why we have to do ds.popback() in recursion this I didn't understood bhaiya

    • @takeUforward
      @takeUforward  Před 3 lety +3

      before calling the recursion, you inserted it into ds, so when the recursion call ends, you need to remove it from ds, or for next calls it will be there. Hence pop back

    • @arlynsneha5052
      @arlynsneha5052 Před 3 lety +3

      @Jaya Dubey I too had the same doubt.... see it like this.. in the last rec call let the ds will be {1 2 3} ...now it should backtrack and go ryt so when it goes back it should go like{ 1 2} ... thats why we pop the last element

    • @avanisingh104
      @avanisingh104 Před 3 lety +2

      Bcs the recursion will go down and down first(and not in the right) and thus will return from the down function calls to upside and hence the ds needs to go back to it's previous state which was without the last element and so the last element is popped

  • @ieltsbaba8400
    @ieltsbaba8400 Před rokem

    I didn't understand the base case. can someone please explain it? how the recursion will stop?

    • @notmyrealname4105
      @notmyrealname4105 Před rokem

      there is no base case,whatever non duplicate ds vector you are forming is pushed into ans vector.