L13. Print all Permutations of a String/Array | Recursion | Approach - 2

  Рет қаралды 349,053

take U forward

take U forward

Күн бұрын

Пікірлер: 274
@takeUforward
@takeUforward 3 жыл бұрын
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/permutationsCppApproach-2 Java Code: github.com/striver79/SDESheet/blob/main/permutationsJavaApproach-2 Approach-1 Video Link: kzbin.info/www/bejne/j3yaaXmLaquZoNk Instagram(For live sessions): instagram.com/striver_79/
@ghj7275
@ghj7275 2 жыл бұрын
Can you please check the below code for Permutation - II problem on leetcode, It fails for [1,2,2,3,3]. class Solution { List res = new ArrayList(); public List permuteUnique(int[] nums) { Arrays.sort(nums); f(0, nums, nums.length); return res; } public void f(int ind, int nums[], int n) { if(ind == n-1) { List li = new ArrayList(); for(int i : nums) li.add(i); res.add(li); return; } for(int i = ind; i < n; i++) { if(i != ind && nums[i] == nums[i-1]) continue; swap(nums, ind, i); f(ind+1, nums, n); swap(nums, ind, i); } } public void swap(int nums[], int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
@ashwinikumar3988
@ashwinikumar3988 2 жыл бұрын
@@ghj7275(i!=ind && nums[i]==nums[i-1] ) works only when array is sorted.here swapping distorts the sorted array so this is not gonna work.
@Anonymous-uj3jx
@Anonymous-uj3jx 2 жыл бұрын
A year back when I saw this question on gfg, I spent nearly 5 hours understanding this solution, and now after seeing your approach I could code it myself, you are a legend man. And you are giving all this for free, I pray to God that you will be blessed with good health and prosperity.
@pcgaming6597
@pcgaming6597 5 ай бұрын
Thank you for this comment cause I though, for me only it's taking 5 hours to understand a question. I think I am wrong now 🤗
@subhadipmaity3253
@subhadipmaity3253 2 жыл бұрын
Sir I think you have no need to say "Please please like this video, and subscribe this channel", those who really understands coding will definitely give value and respect to you. Thank You so much Sir for all the amazing series.
@mohammedwaseem8599
@mohammedwaseem8599 3 жыл бұрын
Hello bhaiya i hope you are doing extremely well
@rishabh_pant
@rishabh_pant Жыл бұрын
😁
@infinity2creation551
@infinity2creation551 Жыл бұрын
Ayeen
@Paradox82827
@Paradox82827 7 ай бұрын
chup k2a
@naveenkamagoud
@naveenkamagoud 6 ай бұрын
@@Paradox82827 😂
@Mohd-12335
@Mohd-12335 Ай бұрын
😂
@abhi007rider
@abhi007rider 2 жыл бұрын
Completed the whole Tree,Graph and Recursion series. Striver you are a gem
@indranilthakur3605
@indranilthakur3605 2 жыл бұрын
how much time it took for you?
@Yag116
@Yag116 Жыл бұрын
did it build your programming logic?
@vishalgowrav
@vishalgowrav 2 жыл бұрын
I solved this question by my own using this approach just by watching first 6 minutes of video,Felt very happy afterwards. Your explainations and approaches are top notch.Thank u for this series Striver
@AVIS_11
@AVIS_11 2 жыл бұрын
this is so true'
@adityamahimkar6138
@adityamahimkar6138 3 жыл бұрын
The moment I heard swapping, I completed the code while only half video was over. I'm showing growth, thanks to you bro :) ✨
@AbhishekYadav-ni5ts
@AbhishekYadav-ni5ts 2 жыл бұрын
Brother what does vector means in line 16 ..... Does it means that the return type will be vector... Please explain to me..
@AbhishekYadav-ni5ts
@AbhishekYadav-ni5ts 2 жыл бұрын
Is it returning multidimensional vector...?? I am confused please help
@adityamahimkar6138
@adityamahimkar6138 2 жыл бұрын
@@AbhishekYadav-ni5ts yes it is a nested vector or multidimensional vector
@AbhishekYadav-ni5ts
@AbhishekYadav-ni5ts 2 жыл бұрын
@@adityamahimkar6138 ohh... Thank u bhai 🙏
@vishalgowrav
@vishalgowrav 2 жыл бұрын
Even i did the same bro!
@tanmaysinghal8370
@tanmaysinghal8370 2 жыл бұрын
damn i just love this guy, he explains full recurssion tree till end.... HATS OFF TO YOU BROTHER
@zeeshanequbal6227
@zeeshanequbal6227 3 жыл бұрын
BONUS: This method can also be used to solve Permutation II problem of Leetcode, where duplicate elements could be present in the array. The only thing to take care in this case is that we are dependent on the sorted order of Array to check for and skip duplicates, so either don't pass the array as reference or restore the original array before exiting. Here is the C++ solution for Permutations-II using this approach. class Solution { public: // Dont pass nums by refernce, cause that will mess up our sorted order. // Or, if passing by reference, then swap ALL positions back so that array remains sorted. void solve(vector &nums, int idx, vector &res) { // Base Case int n = nums.size(); if(idx == n) { res.push_back(nums); return; } // Recursive Step for(int i = idx; i < n; i++) { if(i != idx && nums[i] == nums[idx]) continue; swap(nums[i], nums[idx]); solve(nums, idx + 1, res); } for(int i = n - 1; i > idx; i--) // Dont need to do this if passing nums by value. swap(nums[i], nums[idx]); } vector permuteUnique(vector& nums) { vector res; sort(nums.begin(), nums.end()); solve(nums, 0, res); return res; } };
@nitwaalebhaiya
@nitwaalebhaiya 2 жыл бұрын
for(int i = n - 1; i > idx; i--) // Dont need to do this if passing nums by value. swap(nums[i], nums[idx]); Thanks. This is awesome.
@parissweetheart96
@parissweetheart96 2 жыл бұрын
@@nitwaalebhaiya Not passing leetcode test case. What is wrong in this. Here is my java code: class Solution { private void recurPermute(int index, int[] nums, List ans) { if(index == nums.length) { // copy the ds to ans List ds = new ArrayList(); for(int i = 0;i
@Rajat_maurya
@Rajat_maurya 2 жыл бұрын
@@parissweetheart96 class Solution { public: void f(vector &v1,vector &v2,int i) { if(i==v1.size()) { v2.push_back(v1); return ; } for(int j=i;ji) && v1[j]==v1[j-1]) continue; swap(v1[j],v1[i]); f(v1,v2,i+1); swap(v1[j],v1[i]); } } public: vector permuteUnique(vector& v1) { vector v2; sort(v1.begin(),v1.end()); f(v1,v2,0); return v2; } }; can you please help me whats wrong in this solution for permutation II
@sohailshaik9
@sohailshaik9 2 жыл бұрын
@zeeshan Can you please explain the reverse swapping I'm not understanding that part
@Believer...
@Believer... Жыл бұрын
i am speechless bro!! no one on youtube want to put that much hard efforts to make us understood. you clear the concept level by level which impact our problem solving tremendously.
@aakashyadav6228
@aakashyadav6228 3 жыл бұрын
Bro please complete the placement series before the placement season. I can guarantee you that this series will be the most watched series in the coding community in next few years. I know you have your health issues and job as well. But please help us all out whenever free. Kudos to you and keep up the good work !
@samwaadvivaad8607
@samwaadvivaad8607 2 жыл бұрын
guruji maan gaye apko! you explained each line i watched 3 video's and i was confused how the i is moving to its next place before recursive call and you just made it clear .....thanks man!
@adityasankhla1433
@adityasankhla1433 Жыл бұрын
Holy Moly. Solved the question after watching just the first 2 mins of the video. Crystal clear explanation and intuition building striver!
@sandeepnallala48
@sandeepnallala48 3 жыл бұрын
raj bro u are really master of Recursion. the way you draw the Rec tree make things easy to understand brother.
@geekyaman2297
@geekyaman2297 3 жыл бұрын
You are none other than god/ best guru for any tier 3 student! Jitna thanx kru kam h bhai apke liye🙏❤❤❤❤
@deweshjha8120
@deweshjha8120 3 жыл бұрын
that's true
@ritikashishodia675
@ritikashishodia675 2 жыл бұрын
True bro he is inspiration to all
@indroneelgoswami5654
@indroneelgoswami5654 4 ай бұрын
Earlier I was not able to code. But, the good thing is that I can code myself after watching the logic only (without watching the java solution). Sir you are great!!
@aryansinha1818
@aryansinha1818 2 жыл бұрын
You explain things at a different level, which is very easy to understand. Thank you, sir. Love and respect always.
@Manishgupta200
@Manishgupta200 Жыл бұрын
Amazing Striver ❤ I'm preety much unsure about TC and SC but now clear after watching your tutorial
@notdumb3182
@notdumb3182 2 жыл бұрын
Hey, I just want to let you know if I make it to good company you will be the main reason behind it. This videos are real gem hope they stay free here on KZbin. Wish you a very good life ahead
@siddharthkhandelwal933
@siddharthkhandelwal933 Жыл бұрын
Thanks for all of your videos. The explanations are great.
@AYUSHKUMAR-xj4wc
@AYUSHKUMAR-xj4wc Жыл бұрын
This is the cleanest approach to solve this problem. I would prefer this one. Thanks Striver❤❤❤❤
@stith_pragya
@stith_pragya 9 ай бұрын
UNDERSTOOD......Thank You So Much for this wonderful video............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@govindmajage2317
@govindmajage2317 3 жыл бұрын
Perfect recursion series tysm bhaiya👍🙏
@shubhamkevadiya9142
@shubhamkevadiya9142 2 жыл бұрын
Best Approach. Can't find more simpler than this !! Thank you Striver
@saketjaiswalSJ
@saketjaiswalSJ Жыл бұрын
2 years old video still ( striver u r literally god brother thank u from the bottom of my heart will meet u surely )😀😀
@sumeetubale3923
@sumeetubale3923 Жыл бұрын
A Big Thank You to Striver Bhaiya for this Amazing series !!!❤❤❤
@rahulgovindkumar3105
@rahulgovindkumar3105 3 жыл бұрын
You are videos are really really really helping me . Plse......Keep making videos like this
@bmishra98
@bmishra98 4 ай бұрын
Base case can also be if(index == candidates.size() - 1) {...}, as when 'index' reaches 'candidates.size() - 1', no change in position of elements occur on further recursive call. Thus, the 2nd last level of recursion can also be treated as the base case.
@kratika_agrawal28
@kratika_agrawal28 3 жыл бұрын
You are videos are really helping me . Keep making videos like this
@athangkulkarni8245
@athangkulkarni8245 11 ай бұрын
Striver, you are an absolute jod! Watched initial explanation and tried to code on my own and coding never felt this easy! Thanks man
@studynewthings1727
@studynewthings1727 Жыл бұрын
Thankyou so much STRIVER, I have understood all the code very well. I able to draw all the function calls made by the function again and again.
@ahrazmalik5807
@ahrazmalik5807 3 жыл бұрын
One of the best teacher on youtube❤️
@awanishtiwari8683
@awanishtiwari8683 2 жыл бұрын
I have much fear 😨 that how does these recursive calls flow but with the cute explanation from your videos I got to know it very efficiently Thanks alot for your efforts
@kushagraverma2772
@kushagraverma2772 10 ай бұрын
thanku sir , i solved the whole question by myself just after listening the hint of swapping technique.
@rudra_anand
@rudra_anand Жыл бұрын
Your teaching skills are exceptional.
@shastriamisha
@shastriamisha 2 жыл бұрын
Amazing explanations, loving the recursion playlist, cant wait to start DP :) Thank you very much for this amazing content.
@sankalpsharma4890
@sankalpsharma4890 3 жыл бұрын
I was trying this question from long time. Thank you so much...
@San-ix7ki
@San-ix7ki 2 жыл бұрын
studied recursion from many resources but was not able to get how to write code from tree there I was able to make tree from code but after striver's series I am able to do that finally...hats off to this man thanks alot..
@thinker-o5p
@thinker-o5p 2 жыл бұрын
god level teaching you cleared all my doubts in one shot
@pranavm002
@pranavm002 2 жыл бұрын
This is very smart solution...probably a solution that will make you stand out!,
@mohitagarwal1888
@mohitagarwal1888 2 жыл бұрын
This was better in terms of consuming less space as well as easier understanding.
@gandhijainamgunvantkumar6783
@gandhijainamgunvantkumar6783 2 жыл бұрын
Thank you so much bhaiya for such a crystal clear and amazing explanation :)
@neyovyas3992
@neyovyas3992 3 жыл бұрын
Please try to upload 1 video daily it will be so helpful
@anujmishra778
@anujmishra778 2 жыл бұрын
raj bhai i really enjoying learning your this series , aap ka video dekh kar lagta hai aap har ek topic ko samjhane me bahot mehnat karte ho bhai, thanks a lot bhai
@sonusah6620
@sonusah6620 Жыл бұрын
No words to express.....GOAT for a reason
@prathamsagar5353
@prathamsagar5353 Жыл бұрын
I like ur style of explaining and it all goes in my head. BUT I am afraid if I will be able to figure all this out in an interview???
@Hari-mm9eo
@Hari-mm9eo 2 жыл бұрын
You are explaining it more clear than others, cheers mate!
@saisubhank8011
@saisubhank8011 8 ай бұрын
I dint understand why we need to reswap? It would be great if you can explain.
@akshitsingh2598
@akshitsingh2598 Жыл бұрын
why do we need to wait for the pointer to go out , we are getting all permutations when pointer is at n-1 , so that could be our base condition.
@TharunMettala
@TharunMettala Жыл бұрын
Thanks for this video man!!! Keeping going forward❤
@parthsalat
@parthsalat 2 жыл бұрын
Thanks God, for making Striver
@lomeshdaheria9960
@lomeshdaheria9960 3 жыл бұрын
Thank you bhai for your great efforts😁🙏❤️
@shanuraj6239
@shanuraj6239 2 жыл бұрын
funny thing was that for me it was the first idea i had before the brute force approach😅
@shubham7668
@shubham7668 2 жыл бұрын
Base condition could be (index=nums.size()-1) Coz basically we are doing nothing in last swap
@chidambarjoshi3470
@chidambarjoshi3470 Жыл бұрын
I have tried another approch using emplace back, vector ans; sort(nums.begin(), nums.end()); do { ans.emplace_back(nums); }while(next_permutation(nums.begin(),nums.end())); return ans;
@abhijeetbasfore6816
@abhijeetbasfore6816 2 жыл бұрын
I solved this question without watching this video. Awesome tutorials
@GeniuslyTensai
@GeniuslyTensai 2 жыл бұрын
Op explanation!!!! When understood the intuition it was really great.
@ShubhamPatidar16
@ShubhamPatidar16 3 жыл бұрын
Thank u so much bhaiya and please bring backtracking problems
@rohanraonallani561
@rohanraonallani561 3 жыл бұрын
Also,try to discuss the heap's algorithm if possible
@ajinkyadeshpande3992
@ajinkyadeshpande3992 2 жыл бұрын
Such a clean solution. Perfection.
@awanishtiwari8683
@awanishtiwari8683 2 жыл бұрын
I hope you are doing extremely well 😀😀😌😌
@debangshubanerjee1311
@debangshubanerjee1311 2 жыл бұрын
why is it rec(index+1) and not rec(i+1), in both combination sum 2 and subset 2 the recursion was rec(i+1) similar approach, confused here...
@rishikumar218
@rishikumar218 Жыл бұрын
This Approach is only work when there is not matters of orders of output(print any order) but if need to print lexographical order it may fails even after sort the array initialy. correct if i'm wrong??
@adityan5302
@adityan5302 2 жыл бұрын
Python solution : Only reffer if you face difficulty in forming the code : class Solution: def permute(self, arr: List[int]) -> List[List[int]]: res = [] n = len(arr) def solve(ind): if ind>=n: res.append(arr.copy()) return for i in range(ind, n): arr[ind], arr[i] = arr[i], arr[ind] solve(ind+1) arr[ind], arr[i] = arr[i], arr[ind] solve(0) return res
@neyovyas3992
@neyovyas3992 3 жыл бұрын
Nice explanation understood both the approach
@devinpadron5
@devinpadron5 9 ай бұрын
Time and space complexity 13:34
@kaichang8186
@kaichang8186 Ай бұрын
understood, thanks for the perfect video
@ksanjay665
@ksanjay665 8 ай бұрын
Most underrated channel 😞😞😞
@prateekkumar4965
@prateekkumar4965 7 ай бұрын
solving question ❌ Building Login✅ 🙇‍♂🙇‍♂🙇‍♂🙇‍♂
@hiteshpatwal9688
@hiteshpatwal9688 6 ай бұрын
Logic ❌ Login Page✅
@aryangoyal2252
@aryangoyal2252 2 жыл бұрын
i have watched till now, solved and understood every approach but confuse when to apply which ie looping, picking not picking and swap
@jeeldasvani5015
@jeeldasvani5015 2 жыл бұрын
watch aditya verma's recursion series for foundation then watch strivers series
@techcode356
@techcode356 Жыл бұрын
Thank YOU !!! It was really helpful
@sumitSharma-ed5mi
@sumitSharma-ed5mi 3 жыл бұрын
very helpful and easy to understand.
@sairamsudireddy6191
@sairamsudireddy6191 2 ай бұрын
coming to time complexity -> isnt the for loop complexity already included in n! ? I understood that for every permutation to transfer into ans it takes n! * n , but i believe for loop complexity is already included in n!
@pratikkore7947
@pratikkore7947 5 ай бұрын
I did have a thought about using swapping but I couldn't be sure that it would produce all permutations without duplicates.... still not sure how it's exhaustive
@SahilSingh-pc1vd
@SahilSingh-pc1vd 3 жыл бұрын
Why are we not maintainig an extra ds(vectords) to store elements then push in our final ans like in previous questions???
@adityamahimkar6138
@adityamahimkar6138 3 жыл бұрын
The reason is we are swapping it in the input array so no requirement of additional storage and also after the work is down we again swap while backtrack, so thus the original array is produced :)
@shwetanksingh5208
@shwetanksingh5208 2 жыл бұрын
No need for additional data structure ds while pushing in ans.....below is a more neat code....btw it goes unsaid that your explanations are just beyond words //Time complexity O(n! x n) //Space complexity O(n) class Solution { public: void solve(vector &nums,int ind,vector &ans) { if(ind == nums.size())//if index is crossing the array boundary then push the current state of permutated numbers //in the array to ans { ans.push_back(nums); return; } for(int i=ind;i
@manozrevella2473
@manozrevella2473 2 жыл бұрын
for(int i=ind;i
@A_Myth963
@A_Myth963 5 ай бұрын
should i memorise these concepts... like i can code a concept easily but i can't think of concept like these on my own..what should i do?
@Atuljyotisagar
@Atuljyotisagar 3 жыл бұрын
What change to existing code will give us unique permutaions??
@Ram-vg5fu
@Ram-vg5fu 3 жыл бұрын
Loved ur videos.. when will u resume doing sde sheet pls reply bro 🙂
@salmankhader1258
@salmankhader1258 Жыл бұрын
Well the previous approach will also work in constant space if we just store the character which we are taking in our current permutation in temp variable and change the char by some dummy char or space and recursively call the same function while picking the char ensure that it is not a space. and while doing backtracking we can change the curr char to temp. so that our input string remains same.
@hari16032
@hari16032 Жыл бұрын
yeah i even tried this, it should give the same complexity as this one!
@AbhishekKumar-yv6ih
@AbhishekKumar-yv6ih 3 жыл бұрын
There is one big benefit of the first approach, it can even work even when we have duplicate elements in the original array(Permutations II on leetcode). Just the value of map will be int instead of boolean. Is that correct?
@zeeshanequbal6227
@zeeshanequbal6227 3 жыл бұрын
We can solve even permutations-II problem using this approach. Checkout my above comment for solution and logic. :)
@popli10
@popli10 Жыл бұрын
best explanation love you bhaiya
@Yogamindmastery
@Yogamindmastery 4 ай бұрын
tu es un genie
@coefficient1359
@coefficient1359 3 жыл бұрын
Understood 👍
@harshagarwal1218
@harshagarwal1218 3 жыл бұрын
Will this work,if given to print permutations in lexicographical order?
@gaishiya7696
@gaishiya7696 3 жыл бұрын
yeah but we need to sort the input string before hand
@anmoljoshi8275
@anmoljoshi8275 3 жыл бұрын
Great explanation. Thanks!!
@rumiNITPatna
@rumiNITPatna 3 ай бұрын
thank u so much striver!
@sahilkhan_cs50
@sahilkhan_cs50 2 жыл бұрын
class Solution { private: void helper(vector a,vector &ds,vector&ans) { if(a.size()==0) { ans.push_back(ds); return; } for(int i=0;i
@arshdeep011
@arshdeep011 Жыл бұрын
Bro you are the best 😍🥰🥰🥰
@sarthak_dms
@sarthak_dms 2 жыл бұрын
man this trick was amazing
@sainipankaj
@sainipankaj 2 жыл бұрын
second approch is much better than 1 approch
@anmolverma075
@anmolverma075 2 жыл бұрын
At 15:18 , why did we take the ds separately , we could have called it together in the function call. Also why did we use another loop to add the elements in the ds?
@venup2813
@venup2813 Жыл бұрын
literally it took me to spend 3 hours to understand
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
Google is lucky to have Striver!
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@deepakchowdary8114
@deepakchowdary8114 3 жыл бұрын
Bro I am preparing for placements ,sde sheet is enough ? or should i have to practice from interview bit plzz replyy
@SuperWhatusername
@SuperWhatusername 2 жыл бұрын
Thank you Striver
@gunratnamore4250
@gunratnamore4250 2 жыл бұрын
thanks striver !!! all doubts cleared :).
@GhostVaibhav
@GhostVaibhav Жыл бұрын
Understood🔥
@abbasnaqvi5381
@abbasnaqvi5381 2 жыл бұрын
what if we change the value of nums array to 11 just to mark it as visited and unmark it when we comeback? will this help in removing the extra bool array space?
L14. N-Queens | Leetcode Hard | Backtracking
36:55
take U forward
Рет қаралды 431 М.
L12. Print all Permutations of a String/Array | Recursion | Approach - 1
19:07
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 89 МЛН
Don't underestimate anyone
00:47
奇軒Tricking
Рет қаралды 16 МЛН
За кого болели?😂
00:18
МЯТНАЯ ФАНТА
Рет қаралды 3 МЛН
L17. Palindrome Partitioning | Leetcode | Recursion | C++ | Java
24:34
take U forward
Рет қаралды 285 М.
Large Language Models explained briefly
8:48
3Blue1Brown
Рет қаралды 449 М.
L11. Subset Sum II | Leetcode | Recursion
30:16
take U forward
Рет қаралды 337 М.
5 Simple Steps for Solving Any Recursive Problem
21:03
Reducible
Рет қаралды 1,2 МЛН
String permutation algorithm | All permutations of a string
14:59
Beginners Should Think Differently When Writing Golang
11:35
Anthony GG
Рет қаралды 123 М.
Next Permutation - Intuition in Detail 🔥 | Brute to Optimal
28:15
take U forward
Рет қаралды 456 М.
I made my own shadertoy in C++
8:02
Low Level Game Dev
Рет қаралды 8 М.
L6. Recursion on Subsequences | Printing Subsequences
25:01
take U forward
Рет қаралды 642 М.
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 89 МЛН