L11. Subset Sum II | Leetcode | Recursion
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
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.
Hi, I am still unable to solve problems on my own. what should I do? 😥😥
@@akmansr7149 practice
@@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 😭
@@akmansr7149 bro i hv also same problem
I suggest follow DSA kunal kushwaha course. You can start from recursion or binary search video.
@@akmansr7149same problem
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.
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
@@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
Damn!! congrats bhai
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 😂😂
@@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
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.
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...
pls tell me how b/c i feel so scared looking at them rn
Everyone is Pro Until the new Question drops in the interview
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/
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.
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?
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.
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 !
i != idx,
instead of above condition,
we can also write i > idx,
which is intuitive.
agree 🤝
Indeed a great explanation, this problem has similarities to the combination sum-II problem. Enjoying the recursion series.
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!
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.
the best channel for competitive programming! thanks a lot brother!
Fantastic explanation.. U made recursion more easy and interesting.. Hats off your to patience
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
Very Very Good Explanation , Very Helpful , keep on making these kind of videos.
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😃
Same here bro. The way he has simplified the whole process is so amazing
Thanks man! You make it so so so easy!
Combination II helped with this one , coded solution without referring video solution👍 developing the intuition
that's true !
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
Thanks a lot bhaiya...
Abhi apka CP sheet kar raha...
SDE Sheet iske baad🙌
Sukriya for all this help.❤️❤️
This is the best placement series!!!!
UNDERSTOOD... !!!
Thanks striver for the video... :)
THANK U SOOOO MUCH FOR WONDERFUL EXPLANATION
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.
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 .
plz anyone explain why the complexity of O(nlogn) to inset into set. OR I missed something at 2:22.
Thanks in advance
for reducing time complexity ....can we use unordered set ?
because all operations like insert will be O(1) ........ can we do that
Thanks for the amazing explanation!
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 🤙😎
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.
Yeah me too faced the same issue . I didn't think there is no base case required.
@@av21015 yeah, i was returning for the base case, thats why it wasnt working
Thanks striver sir for explaning it the best way possible💯💯
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?
understood
Thank you striver for such an amazing explanation..
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 🤐
able to solve this without seeing ur video!! cheers to your teaching method
Well Explained, Thanks ❤️
but how' s the time complexity of converting hashset to List is ml* logm ?
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.
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?
this question is less of recursion but more in optimising the input and output
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.
in time complexity 2^n log 2^n is also added for sorting?
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.
hi man, thankyou for making video for us even if your not able to speak loud after tumor operation. ❤
love you bhaiya
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!
ALWAYS TRY TO DRAW RECURSION TREE OF WHATEVER CODE COMES TO YOUR MIND THEN ONLY YOU WILL GET TO KNOW WHERE YOU ARE WRONG
whats the link to previous video, not able to find it
Beautifully Explained!
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
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.
simple as that, if array does not contains duplicates use pick and non pick method , if it has duplicate use for loop method :)
I have a question? How would this recursion stop if theres no base case unable to understand?
Because the for loop will not get executed and hence no further recursion calls will be made
Great explanation
But I think SDE sheet is getting difficult now 🥺😬😬
Did u finish?. How is placement going?
@@tekken1935 i am in first year
I am on dp
Been 2 years how you doing
Striver You are really Amazing..!
void f(vector &v1,vector &ans,vector &ds,int i)
{
ans.push_back(ds);
for(int j=i;j
same problem here.. did you got the solution?
actually that should j+1 instead of i+1
@@s.hariharanreddy5439 yes you are correct
@@s.hariharanreddy5439 thanks it's helps me a lot
Isn't the time complexity O( n * 2^n ) since we are pushing a vector every time recursive function is called.
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 ...?
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.
C++ code starts at 25:30
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?
to avoid reference sharing
from index we have to search (all combination)till last element hence func(i+1,...) in this instead of index+1?
You picking i, so i+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
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.
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
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
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.
@@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.
@@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.
@@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😊
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
Absolute masterclass...
Anybody can help me what is the difference between index and i in this qtn?
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 :)
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
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.
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...
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 ?
please use light color ink on dark background...
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.
total elements in nums are less then 10 as given in the constrains, so sorting 10 elements would not take much time
even the powerset method with bit manipulation without recursion works here, which time complexity is 2^n * n
Understood clearly.
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?
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?
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.
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
//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
i dont get it why the index of [1,2] is 2 in the video, can anyone explain for me?
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.
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.
same problem code is tottaly different from tree
wow, thank you!
stll cant understand why you did i!=ind these both are same or not?
@takeUForwad can can recursive code be written without base case? Please explain this.
++++
@takeUForward
understood!!
I tried this appproach but i am getting repetitive sub_sets, how can i improve this.
Can anyone help why there is no base case for the recursion
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
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
I have a doubt!! What if we remove the duplicates from nums array in the beginning itself
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.
Hare Krishna! Great!
Why there is no base case in this recursion ?
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
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.
i think you are just using two recursive calls while there can be n of them
so try using a loop as he explained
yooo! i was able to solve it on my own
Nice Explanation!
Thanks Bhaiya
Understood ❤
What's the purpose of making deep copy here? How actually it required?
Hi striver,
why we dont add the base condition in this problem ?
i.e if (index == nums.length - 1) ?
same doubt
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
Complexity analysis at 20:30
Why we have to do ds.popback() in recursion this I didn't understood bhaiya
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
@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
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
I didn't understand the base case. can someone please explain it? how the recursion will stop?
there is no base case,whatever non duplicate ds vector you are forming is pushed into ans vector.