Print unique subsets And Variations
Vložit
- čas přidán 30. 06. 2020
- Link: / adityaverma
Video Pdf Notes And Code: / 38828164
Problem Description: practice.geeksforgeeks.org/pr...
Given an array of integers that might contain duplicates, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
The subsets must be sorted lexicographically. .
------------------------------------------------------------------------------------------
Here are some of the gears that I use almost everyday:
🖊️ : My Pen (Used in videos too): amzn.to/38fKSM1
👨🏻💻 : My Apple Macbook pro: amzn.to/3w8iZh6
💻 : My gaming laptop: amzn.to/3yjcn23
📱 : My Ipad: amzn.to/39yEMGS
✏️ : My Apple Pencil: amzn.to/3kMnKYf
🎧 : My Headphones: amzn.to/3kMOzM7
💺 : My Chair: amzn.to/385weqR
🛋 : My Table: amzn.to/3kMohtd
⏰ : My Clock: amzn.to/3slFUV3
🙋🏻♀️ : My girlfriend: amzn.to/3M6zLDK ¯\_(ツ)_/¯
PS: While having good gears help you perform efficiently, don’t get under the impression that they will make you successful without any hard work.
Bhai fit-jee ke baad ab jaakar aisa teacher mila hai. :' )
VERY TRUE
Agreed
Itna detailed analysis kahi aur nhi milega.. guarantee
Pep Coding par sumeet sir
@@VKBMath ya bro he is also best 🙂
ghanta
Bhai apne recursion ko bahut easy kar diya he me bahut kam use karta tha recursion but now i am comfortable with recursion 😅
Hi Aditya, It would be very helpful if you could also include the time and space complexity in your video as this will definitely increase the quality of your content and will also be helpful for everyone.
mostly recursive code complexity comes as exponential .
kahan placed ho bhai aajkal?
17:10 "Its her choice" - I laughed so hard🤣. Thank you for making these amazing videos. You make things a cakewalk. I am preparing for interviews for product based companies now and one day when I get there, I am definitely returning all the favour of learning from you!🙌
++,
sun meri baat its her choice
hahahahaha
@@vedantgolash6084 hue hue hue
I have never finished any youtubers playlist till now, but completed this one, the things look so easy. Thank You.
How can someone dislike a video as good as this? :(
Dislikes are from Neha Dhupia fans
Instead of creating map and vector,then comparing that string is present in map or not, we can simply use Set which automatically removes duplicates and also sort the strings.
But time complexity will increase as set takes o(logn) for insertion which map takes o(1) for insertion
@@anaszubair582 but for checking vector is already present or not in map takes O(logn) and it requires extra space, hence set is better
@@ashishchhikara7829 we will use unordered map which take o(1) for searching and yes It will take extra space but it is faster then set
@@anaszubair582 sorry bro for misunderstanding.....i used to code in python, and it have dict data structure, so i thought in that way.......i know nothing about C++ or java........from python point of view ....i think set will be better
@@ashishchhikara7829 even in python dict has complexity o(1) for insertion and searching
I am relaxed seriously for future technical interviews coz Aditya explain so well that each concept is mastered.
you are great sir I love the way you teach earlier I used to memorize questions but I now I understand it.
I can see people demanding for other topics in the comment section .
But i am here to appreciate the efforts you are making selflessly .
Thanks a lot for such a great explanation and generalize all type of quesitons
Thanks for the playlist sir....your work is extremely good
Bhai backtracking ka playlist placement session se pahle aajayega ?
simple code just by using map for unique subset with comments:-
#include
using namespace std;
void subset(string ip,string op,map &m)
{
if((int)ip.size()==0)
{
m[op]++;
// only these two lines I added additionally checking whether string was present before or not.
if(m[op]==1)
// If not then print. Rest is full same code as before just declare map and pass by reference.
cout
could use set/unordered_set
can u explain first line in if()
@@geekylearner3596 you can directly write ip.length()
\
Sachme bhaiya maja agaya itna details me janne k baad 😇😘
bhai ki hr video is lit... and wo 13:36 p knapsack wali problem yaad meko v aa gyi..
You are wonderful teacher 👏👏
The best explanation I ever found ... thanks a lott please make series on graph
meanwhile u can refer wiilliam fiset for graphs
Bhayya 80k subscribers hogaye hain
Please abseto graphs start kardijiye
Lockdown me utna bhi mushkil nahi hoga
Bhai isse bhadiya content aur kahin nahi mila aajtak
Bro give timestamps if possible, BTW suuup explanation 👌👌
the content is heaven for people like me who struggled in recursion, but till now we were familiar with IBH method is there any type of corelation between this rec tree method and IBH one if anyone could tell it would be of great help to memorise it
Great teacher
*Unique subsequences vs unique combinations/subsets*
Suppose the original given string is abab
Then the total subsequences will be
void, a, b, a, b, ab, aa, ab, ba, bb, ab, aba, abb, aab, bab, abab
Now the unique subsequences will be
void, a, b, ab, aa, ba, bb, aba, abb, aab, bab, abab
But the number of unique combinations (or unique subsets) will be less than unique subsequences
The unique combinations here will be
void, a, b, ab=ba, aa, bb, aba=aab, abb=bab, abab(=aabb)
To find the unique combinations we can sort the string abab first to aabb
Then the resulting unique subsequences will unique combinations
void, a, b, aa, ab, bb, aab, abb, aabb
Java 8 solution for printing unique subsets:
public class PrintUniqueSubsets {
public static void main(String[] args) {
Set uniqueSubset = new HashSet();
uniqueSubset = printUnique("aab", "", uniqueSubset);
System.out.println("Unique subsets: ");
uniqueSubset.forEach(System.out::println);
}
public static Set printUnique(String ipStr, String opStr,
Set resMap) {
if (ipStr.isEmpty()) {
resMap.add(opStr);
return new HashSet();
}
String opStr2 = opStr;
opStr2 += ipStr.charAt(0);
ipStr = ipStr.substring(1);
printUnique(ipStr, opStr, resMap);
printUnique(ipStr, opStr2, resMap);
return resMap;
}
}
This wont work for input like "aaba". Your approach will still print duplicate subsets.
problem link : practice.geeksforgeeks.org/problems/subsets/0
BEST EXPLANATION EVER
IT'S HER CHOICE :')
This content is like heaven for the brain! Godspeed.
Great explanation! Another option to map and set is to simply sort the input and then skip all duplicates of an element
That would give incorrect answer eg: Dry run your approach for "aab" [HINT: Your approach would probably skip "aa", but that must be present]
@@TheAdityaVerma Oh yes! I was thinking of no duplicates in OUTput, not INput. My bad!
best video ever!!
thanks for info i was somehow confused about subsequence
oo bhai
its her choice 🔥🔥
hi sir i think you missed saying that if the input string with duplicates is not in sorted order then it must be sorted first before finding the subsets
7:23 Don't know about right but I think I can easily left the code 😆.
jk bhaiya. OP content 🔥🔥🔥
thanks a lot
Thank you...
solution for leetcode subsets :-
class Solution {
public:
vector ans ; //global ans bana liya asseseble for all
void generate(vector ip,vector op)
{
if(ip.size()==0)
{
ans.push_back(op);
return;
}
// int pick ke jgh ab vector hoga
vector notpick = op;
vector pick = op ;
pick.push_back(ip[0]); // ab push_back ip[0] mtlb 1 row wala pura aa jyega
ip.erase(ip.begin()+0); // pop wahi begin se leke + 0 tak
generate(ip,notpick);
generate(ip,pick);
}
vector subsets(vector& nums) {
vectorop;
generate(nums,op);
return ans;
}
};
we can use unordered_set instead of map and a vector and then create a iterator for unordered_set to print unique items
so much addictive videoes...........
How can we use subset solution for finding powerset, subset, subsequence? They would have different results right? Example if answer demands ab & ba both, then?
thankyou sir so much
laajawaab, kya padhate ho aditya sir
how to print all the subsets?
how can we do the same as subsequece, as we know both are different??
there are 2^n subsequences possible while n(n+1)/2 substrings possible
Solution for leetcode subsets 2 :-
class Solution {
public:
set ans ; //global bana diya taki bar bar recursion me pass nhi karna pade
void generate(vector ip,vector op)
{
if(ip.size()==0)
{
sort(op.begin(),op.end()); //odering of output bhi matter krta hai set ke liye nhi
ans.insert(op); //abki baar set me insert kar rhe hai
return;
}
// int pick ke jgh ab vector pick/notpick hoga
vector notpick = op;
vector pick = op ;
pick.push_back(ip[0]); // ab push_back ip[0] mtlb 1 row wala pura aa jyega
ip.erase(ip.begin()+0); // pop wahi begin se leke + 0 tak
generate(ip,notpick);
generate(ip,pick);
}
vector subsetsWithDup(vector& nums) {
vector op;
generate(nums,op);
vector finalans; //return ko vector of vectror me karana hai to ...
for(auto it : ans) //set se final ans me transfer
{
finalans.push_back(it);
}
return finalans;
}
};
can u please explain why are we using sorting ..it wasnt mentioned in the question right??
22:42 set is a better option here.
In the first approach, instead of creating another vector and using map, I think we can just store all the elements in unordered_set which has amortized O(1) for insert and at the end we can just copy all the elements from our set to answer vector
bhai coding nahi karwayi apne lekin, concept kafi accha karwaya! maza aagya bhai ! crash course type ke liye acchi series h
bhai aapne code nhi dia, ye bahut galat kia,. kam se kam code toh de dete... bharat achrya wali strategy laga di, adha content dedia baki ke liye fasa dia :-(
waah waah. nice reference through memes. makes the concepts solid
it'll be great if you can mention the links to the other videos you reference in a video, thanks
it's her choice 😂😂bhayya roaster
It will be tricky to solve it if the input is List and the output is
I understood that you formed new instances as lists are mutable and change in place unlike string. But how did you decide to form new instance here "var op1 = new List (output);" and not here " result.Add (output)".
If yu could please explain this I would be greateful
@Pankaj Bisht
Thanks!! helped a lot
We can also use set in the place of map as it will be more efficient.
Around 18:30, you mentioned that in a subset order doesn't matter, while it is the other way around. Order matters, that's why "ac" is different from "ca".
Also important point to mention, in case of substrings and subsequences, you need to remove some cases from the last level of the tree where input is empty string. and then build your induction around that.
Any tips how to solve questions , i feel like i am not making any progress
thank you.
unordered_set use karsakte hae na map k jagah
11:28 Nice Drawing : )
Agar koi larki kre to it's her choice 😂😂nice one
what is mean by in place string ??
Unique Subsets | Practice | GeeksforGeeks for this question, when we are erasing first element of input till it become zero, As we know erasing at first index will costs O(n) time, so is there any other way @Aditya Verma to reduce the time complexity, like in discussions I have seen some are doing without erasing the input
class Solution {
public:
vectorres;
void solve(vectornums,vector&op){
if(nums.size() == 0){
res.push_back(op);
return;
}
vectorop1 = op;
vectorop2 = op;
op2.push_back(nums[nums.size() - 1]);
nums.pop_back();
solve(nums,op1);
solve(nums,op2);
}
vector subsets(vector& nums) {
vectorop;
solve(nums,op);
return res;
}
};
start from the last element and use pop_back() which will cost you O(1) time only
can we somehow do this problem without using extra data structure to filter out the unique? in recusrion itself if we can have some condition to not check for duplicates?
yes , we can do that. Sort the array first and then dont recurse for an element if you had already done it ( sorting the input arr can help us to determine quickly if we had recursed for a similar element earlier or not )
Bhai ek interaction video rakh lo
can anyone please share their java code which got accepted on GFG
Baaki sbka thik hai , smjh gye ek taraf bhai ka "COOL" taraf
in 18:35, did you mean print "subsequence" in both cases, instead of "subset"?
The pdf notes are all paid na?? PLEASE HELP
Guys can anyone update here with the latest code for this problem on leetcode using hashmap and the same procedure which Aditya did?
Hi Aditya , please make backtracking videos as well
But our only choice for learning is Aditya verma
17:15 Aditya bhaiya is Also a Neha Dupia Fan 😂😂
code:
public:
set s;
void solve(vector ip, vector op){
if(ip.size() ==0){
s.insert(op);
return;
}
vector op1 = op;
vector op2 = op;
op2.push_back(ip[0]);
ip.erase(ip.begin() + 0);
solve(ip,op1);
solve(ip,op2);
return;
}
//Function to find all possible unique subsets.
vector AllSubsets(vector arr, int n)
{
// code here
sort(arr.begin(), arr.end());
vector op;
vector ans;
solve(arr, op);
for(auto i: s){
ans.push_back(i);
}
return ans;
}
brother it is working but giving TLE.
function withoutduplicates(idx, arr, ans, dummy) {
ans.push(dummy.slice());
for (let i = idx; i < arr.length; i++) {
if(i>idx&&arr[i]==arr[i-1]){
continue;
}
dummy.push(arr[i]);
withoutduplicates(i+1, arr, ans, dummy);
dummy.pop();
}
} js code simple
11:00 Substring vs Subsequence vs Subset
Bhaiya backtracking ki video bna do plz placement time aane wala hai
Kohi code send kar sakta hai ky muje unique subset string ka?
Adity bhai is string me 3 elements leke batado na keisa hoga ...just explain kardo ham code karlenge.....
Ye 3 elements keliye Kruse tree banau samajh me nehi aa raha
Damnnn bro
instead of using a set/map to remove duplicates , we can sort the input string and skip same consecutive elements.
That would give incorrect answer eg: Dry run your approach for "aab" [HINT: Your approach would probably skip "aa", but that must be present]
neha dhupia ko recursion aata hai?
Will the above map thing work for test case : 4,1,4,4,4
nope will not work for above
sort input string before sending to solve will fix it :) sort( nums.begin(), nums.end());
Its her choice 😁😁
why not jut put the subset in a ordered set and print the set
🤣🤣🤣Its her Choice.. Neha Dhupia shoud be proud!!😆😆
set wali method TLE de deti hai large inputs par :
unordered_map
This approach is giving TLE in gfg
struct VectorHasher {
size_t operator()(const vector& V) const {
size_t hash = V.size();
for (auto i : V)
hash ^= i + 0x9e3779b9 + (hash > 2);
return hash;
}
};
class Solution
{
public:
void solve(vector ip, vector op, unordered_set& ans)
{
if(ip.size()==0)
{
ans.insert(op);
return;
}
vector op1 = op;
vector op2 = op;
op2.push_back(ip[0]);
ip.erase(ip.begin()+0);
solve(ip, op1, ans);
solve(ip, op2, ans);
}
//Function to find all possible unique subsets.
vector AllSubsets(vector arr, int n)
{
sort(arr.begin(), arr.end());
unordered_set ans;
vector ans_vec;
vector ip = arr;
vector op;
solve(ip, op, ans);
for(auto x : ans)
{
ans_vec.push_back(x);
}
sort(ans_vec.begin(), ans_vec.end());
return ans_vec;
}
};
const arr = [1,2,3]
const solve = (ip, op, res) => {
if(ip.length === 0){
res.push(op)
return
}
let op1 = op, op2 = op
op2.push(ip[0])
ip.shift()
solve(ip, op1, res)
solve(ip, op2, res)
}
let op = [], res = []
solve(arr, op, res)
console.log(res)
Why this approach for numbers is not working 😕?
Simple C++ Code
I have used Set
#include
using namespace std;
string solve(string str,string op,set&st){
if(str.length()==0){
st.insert(op);
return op;
}
string op1=op;
string op2=op;
op2.push_back(str[0]);
str.erase(str.begin()+0);
solve(str,op1,st);
solve(str,op2,st);
return op;
}
// c a ac a ac aa aac
int main(){
string str;
cin>>str;
string op=" ";
setst;
solve(str,op,st);
for (auto it = st.begin(); it !=st.end(); ++it)
cout
program to print all substrings recursively. Please help me with it.
// Program to print all substrings Recursively
#include
#include
#include
using namespace std;
void solve(string output, string input, set &arr, int selected)
{
if (input.length() == 0)
{
arr.insert(output);
return;
}
string op1 = output;
string op2 = output;
op1.push_back(input[0]);
input.erase(input.begin());
if (selected == 1)
{
solve(op1, input, arr, 1);
}
solve(op2, input, arr, 0);
}
int main()
{
set arr;
int selected = 1;
string input = "", output = "abcdefg"; //Initial Input and output Respectively
solve(input, output, arr, selected);
set::iterator itr;
for (itr = arr.begin(); itr != arr.end(); itr++)
{
cout
void sub(string ip, string op, bool path, int prev){
if(ip.size()==0){
cout
@@tejasjhamnani7724 this substring of subsets unique?
Any pls share the c++ code of this problem
#include
using namespace std;
void subset(string str,string output,vector &v)
{
if(str.length()==0)
{
v.push_back(output);
return;
}
string op1=output;
string op2=output+str[0];
str.erase(str.begin());
subset(str,op1,v);
subset(str,op2,v);
}
int main()
{
string str,output=" ";
cin>>str;
vector v;
subset(str,output,v);
vector unique;
map m;
for(int i=0;i
Thanks @@@nitingupta1417
@@nitingupta1417 so nice of you :-)
@@abhisheksuryavanshi9675 welcome 😇
@@abhayrai1724 welcome bro 😇😇
17:15 Neha Dhupiya Meme 👍😁😁
17:14
Bhaiya ye to sirf subsequence hua na .
What about all subsets.
Hi, please share the JAVA code for the problem.
Thanks!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Subsets {
public static void main(String[] args) {
solveSubsets("abc", "");
}
static void solveSubsets(String input, String output){
List inputList = new ArrayList();
if(input.length() == 0){
inputList.add(output);
System.out.println(inputList);
return;
}
solveSubsets(input.substring(1), output);
solveSubsets(input.substring(1), output+input.charAt(0));
return;
}
}
@@farazahmad9734 how to do this with Arraylist instead of string ?
@@DINESHKUMAR-gw1kz wo sirf ldki ko btayega 😂
@@amanshaw8496 epic reply bro 😂😂
It's her choice 😂😂😂
its her choice😂😂
Lexi... 😂😂😂
Neha dhupia disliked this video with 7 others !! coz its her choice
GETTING TLE in GFG in this code:
(for PRINT UNIQUE SUBSETS)
void solve(vector ip, vector op, vector& v)
{
if(ip.size()==0)
{
v.push_back(op);
return;
}
vector op1=op;
vector op2=op;
op2.push_back(ip[0]);
ip.erase(ip.begin() + 0);
solve(ip, op1, v);
solve(ip, op2, v);
return;
}
vector AllSubsets(vector A, int n)
{
// code here
vector v;
vector op={};
sort(A.begin(), A.end());
solve(A, op, v);
set s;
int size = v.size();
for(int i = 0; i < size; ++i )
s.insert(v[i]);
v.assign( s.begin(), s.end() );
return v;
}
Try this :)
struct VectorHasher {
size_t operator()(const vector& V) const {
size_t hash = V.size();
for (auto i : V)
hash ^= i + 0x9e3779b9 + (hash > 2);
return hash;
}
};
class Solution
{
public:
void solve(vector ip, vector op, unordered_set& ans)
{
if(ip.size()==0)
{
ans.insert(op);
return;
}
vector op1 = op;
vector op2 = op;
op2.push_back(ip[0]);
ip.erase(ip.begin()+0);
solve(ip, op1, ans);
solve(ip, op2, ans);
}
//Function to find all possible unique subsets.
vector AllSubsets(vector arr, int n)
{
sort(arr.begin(), arr.end());
unordered_set ans;
vector ans_vec;
vector ip = arr;
vector op;
solve(ip, op, ans);
for(auto x : ans)
{
ans_vec.push_back(x);
}
sort(ans_vec.begin(), ans_vec.end());
return ans_vec;
}
};
Try Passing the vectorop in solve() by reference i.e.
void solve(vector ip, vector& op, vector& v)
@@chakravarty-with-a-v How does by passing reference worked?
@@spiral546 passing by reference will not create a copy. Function will work on the original data. If you pass by value then copies will be generated. This will cause a problem for large inputs because copying is done repeatedly taking memory.
void solve(vectorin,vectorop,set& ans){
if(in.size()==0){
sort(op.begin(),op.end());
ans.insert(op);
return;
}
vectorop1=op,op2=op;
op2.push_back(in[0]);
in.erase(in.begin()+0);
solve(in,op1,ans);
solve(in,op2,ans);
}
//each mother fucking subset should be sorted
vector AllSubsets(vector in, int n)
{
vectorans1;
setans;
vector op;
solve(in,op,ans);
ans1.assign( ans.begin(), ans.end() );
return ans1;
}
Java Version for this approach
class Solution {
List res;
Set ans;
void solve(ArrayList ip,ArrayList op)
{
if(ip.size()==0)
{
if(ans.contains(op)==false){
ans.add(op);
res.add(op);
}
return;
}
ArrayList op1=(ArrayList)op.clone();
ArrayList op2=(ArrayList)op.clone();
ArrayList ip1=(ArrayList)ip.clone();
op2.add(ip.get(0));
ip1.remove(0);
solve(ip1,op1);
solve(ip1,op2);
return;
}
public List subsetsWithDup(int[] nums) {
Arrays.sort(nums);
res=new ArrayList();
ans=new HashSet();
ArrayList ip=new ArrayList();
Arrays.stream(nums).forEach(ip::add);
ArrayList op=new ArrayList();
solve(ip,op);
return res;
}
}