String Permutation Algorithm

Поделиться
HTML-код
  • Опубликовано: 30 сен 2024
  • / tusharroy25
    github.com/mis...
    github.com/mis...
    github.com/mis...
    www.educative....
    Write a code to generate all permutations of given string in lexicographically sorted order with repetition of characters in the string.

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

  • @learningguitar562
    @learningguitar562 8 лет назад +419

    came looking for guitar techniques (finger permutations)
    stayed for the computational algorithms

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

    ghood man ghood, you are rheally an amazing theacher, hats off to you thushar...

  • @MrKrecikKret
    @MrKrecikKret 8 лет назад

    Amazing work, thanks for all the effort you've put into making this video!

  • @MrDishajain
    @MrDishajain 8 лет назад

    Awesome Video Tushar :) Excellent explanation of code . Now my concept is clear .

  • @leozilla
    @leozilla 5 лет назад

    Very good explainations! Thank you very much for taking the time to make this videos! *thumbsup*

  • @himanshuverma31
    @himanshuverma31 5 лет назад

    How do you make the GUI in which you were explaining the working of the code? Its a really cool way of explaining things :)

  • @techchamp4508
    @techchamp4508 4 года назад

    I got lost 4:51, wait, can someone explain me why not start at third depth ..? please...

  • @shobhitchaturvediindia
    @shobhitchaturvediindia 8 лет назад

    YOur Videos are awesome

  • @curiosull
    @curiosull 6 лет назад +127

    He will not go trough all permutations, no way .... Wait...he is 😀

    • @HARSHITKUMAR-wj4ex
      @HARSHITKUMAR-wj4ex 4 года назад +1

      :) :) LOL!!!

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

      Actually I think it is important for us since it helps us understand recursion much more clearly.

  • @廖俊翔-e1w
    @廖俊翔-e1w 7 лет назад +141

    A lot of online lectures of great universities expect us to be smart, so they don't go into the problems as detailed. But yes, many of us are that stupid and videos like this are exactly what we need. Really helps me visualize and understand recursion better. Thanks!

    • @jvsnyc
      @jvsnyc 6 лет назад +6

      Nobody is smart in every way, there's bound to be lots of people who can benefit and make use of the knowledge that would find some of the more abstruse or obscure presentations useless to them. This is a great video.

    • @uzairakram899
      @uzairakram899 5 лет назад +3

      No they simply don't have the time and so they expect you to do your own research. Although I do think they should provide a reference.

  • @lalitdudheria7955
    @lalitdudheria7955 8 лет назад +41

    I feel happy every time there is something I don't understand and there is a video by you explaining it. :)

  • @cocoarecords
    @cocoarecords 5 лет назад +10

    The algorithm is:
    Remove the first letter
    Find all the permutations of the remaining letters (recursive step)
    Reinsert the letter that was removed in every possible location

  • @akhilguptavibrantjava
    @akhilguptavibrantjava 8 лет назад +19

    Cool. This tutorial made me understand backtracking like charm. Hats off tushar.Keep doing the good job

    • @RockBrentwood
      @RockBrentwood 4 года назад

      Too complicated. This is much simpler!
      // Found at a UFO crash site.
      // All permutations of 5 items generated.
      #include
      #define N 5
      int main(void) {
      int X[N], Y[N];
      for (int n = 0; n < N; n++) X[n] = Y[n] = n;
      Show:
      for (int n = 0; n < N; n++) printf(" %d", X[n]); putchar('
      ');
      for (int n = 0; n < N; n++) {
      int Xn = X[n]; X[n] = X[Y[n]], X[Y[n]] = Xn;
      if (--Y[n] >= 0) {
      int Xn = X[n]; X[n] = X[Y[n]], X[Y[n]] = Xn; goto Show;
      }
      Y[n] = n;
      }
      return 0;
      }
      (The aliens cited are over here: ruclips.net/video/9dTDhCKBA_c/видео.html )

    • @Rhythmswithruby
      @Rhythmswithruby 4 года назад

      @@RockBrentwood That's basically the same concept except using nested for-loop instead of recursion. Also the variable names are so obscure, it's more difficult to read than Tushar's code at the end of the video.

  • @abhishekj5325
    @abhishekj5325 8 лет назад +14

    Your effort is highly appreciable :)

  • @tomislavzoricic5656
    @tomislavzoricic5656 8 лет назад +13

    Great video as usual!
    Could you make time to create video about big numbers (adding, subtracting, multiplication and division)?
    It would help a lot of guys using c++

    • @tomislavzoricic5656
      @tomislavzoricic5656 8 лет назад

      +Tushar Roy Yes, for example to be able to solve SPOJ problem JULKA

    • @cariyaputta
      @cariyaputta 7 лет назад +3

      I suggest just use Java for big numbers, it's very simple.

    • @tomislavzoricic5656
      @tomislavzoricic5656 7 лет назад +2

      I agree, but I wanted to see the algorithm in action.
      Division gives me headache :)

  • @ShaheenGhiassy
    @ShaheenGhiassy 7 лет назад +3

    For anyone interested in a JavaScript implementation: gist.github.com/sghiassy/669cae13af2632a3ee16b0c633982343

  • @yusufsipahi3916
    @yusufsipahi3916 5 лет назад +3

    Hello,
    The only missing thing I guess is you do not clear the last value in "result" array when backtrack happens. Using stack seems more appropriate I guess.
    Thanks for the share. You did very good job!!!

  • @asahikitase5398
    @asahikitase5398 4 года назад +1

    thanks bro, usually I set 1.25 speed for youtube videos, but for you, I have to set 0.75. lol.

  • @Arunk054
    @Arunk054 6 лет назад +3

    Definitely appreciate the effort this guy has put in. I havent seen anyone teaching with so much patience.

  • @trybeatingthis
    @trybeatingthis 5 лет назад +2

    According to his algorithm its more like O(k^2 * k!). There are k*k! function calls, but each function loops through k times to see what values have been used before.

  • @darrenlackey586
    @darrenlackey586 5 лет назад +3

    I've watched many algorithm tutorial videos and this is one of the best. Really appreciate how thorough and detailed it on top of presenting it in an organized manner.

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

    this is an awesome explanation hat off Tushar

  • @TechiesEscapades
    @TechiesEscapades 4 года назад +1

    Hi, Thanks for the explanation. I have a doubt too, I was trying it for input AABC, but according the coding logic given, result arrays is of size 3 and prints the combination in 3 letters combination, but isn't the output supposed to be 4 letters combinations?

  • @CodeF416
    @CodeF416 5 лет назад +2

    What is the goddamn time complexity my man?

  • @saikishore3954
    @saikishore3954 4 года назад +1

    Nice explanation,
    Incase if any one missed the following point
    Sorting of the given input string is done through Treemap. permuteUtil function prints distinct permutations of a string lexicographically only when the input string is sorted.

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

    Great video - thank you!
    As you expand the permutation graph, I'd suggest you add some sort of 'divider' (removal tape?) to provide an indicator of level.
    great content!

  • @Leo2002cn
    @Leo2002cn 5 лет назад +1

    This is a very intuitive and understandable algorithm. However, it is not optimal for space complexity due to the extra count[] array to store which chars are used or not. There are more space efficient algorithms for permutation.

  • @crazywasy
    @crazywasy 8 лет назад +1

    Tushar, can you please make these days a video about P, NP, NP complete and NP hard algorithms? From you i can understand them much better than even my university professors. Thank you!

  • @MixedMatchedVideos
    @MixedMatchedVideos 8 лет назад +1

    Simply amazing videos. I tried to get the feel of recursion for ages, and finally your video did it.
    Really love the format of your videos and your step-by-step approach of explanation is really what makes learning fun.
    I have tried other channels like saurabhschool etc, but your explanation suits me more.
    One minor suggestions though: if after each video you can leave us with practice problems of similar kind.
    For example, now I've understood this problem and can code it easily. But it will really make my understanding even better if I can apply this knowledge to 2-3 different problems (which uses the same logic). So few practice problems of similar kinds would help.

  • @044_karan9
    @044_karan9 4 года назад +1

    Excellent explanation .. Thanks for putting so much effort to explain :)

  • @sunitapanda7363
    @sunitapanda7363 5 лет назад +1

    HI Tushar, its very helpful but can u please write the code in c++

  • @algorithmscasts902
    @algorithmscasts902 4 года назад

    Made a detailed video explaining a general method to solve backtracking problems that would be helpful to watch after this here ruclips.net/video/fahWlqwOvHo/видео.html

  • @saifulhasan2532
    @saifulhasan2532 6 лет назад

    One more soultion:
    import java.util.*;
    class PermutationDupPrintWithoutDup{
    public static void main(String[] args){
    String s="AABC";
    HashMap hm=new HashMap();
    for(int i=0;i0){
    hm.put(c,count-1);
    PrintPerm(hm,prefix+c,remaining-1);
    hm.put(c,count);
    }
    }
    }
    }

  • @kritikachugh1015
    @kritikachugh1015 4 года назад

    public static void permutation(String str) {

    permutation("", str);
    }
    private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
    for (int i = 0; i < n; i++)
    permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
    }
    public static void main(String args[]) {
    permutation("AABC");
    }

  • @anandreddy4235
    @anandreddy4235 7 лет назад

    Try with this solution
    public class Permutaion {
    public static void main(String[] args) {
    permutate("AABC".toCharArray(),0,3);
    }
    public static void permutate(char c[],int l,int r){
    if(l==r){
    System.out.println(c); }
    else{
    for(int i=l;i

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

    Hi verygod , but @21.35 needed to explain about backtracking , how permute(0,1,1) count[i--] -->permute(0,0,0) prints -->permute(0,0,1)(i who does count[i++] to be back in state , this one is missing in explanation of code.

  • @tekk7989
    @tekk7989 4 года назад

    0:33 What formula is this? If we have AABC, we will have 4!/2! permutations, or 12 permutations. It makes sense, bc if we had 4 unique letters, we would have 4! permutations, but since we have 2 A's, we divide by 2. But what is the formula?

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

    what I am not convinced about is why should we manually increment the count[i] at the end of the recursion? Won't the previous recursion state of this count will be persisted just like result[] ? Why should we manually decrement it?

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

    Soooo...Cantors diagonal argument that proports to prove that there are many infinities relies on just such a list. The problem is that for Cantor to be right the list of permutations MUST be square. That is to say each row must have the same number of entries as each column in order to, diagonally, cover every possible permutation in the list. But as we can see, any such list of permutations on a set (row) will grow by the factorial downwards as it iterates to the right by the addition of each singular element bitwise. This process can never produce a square matrix. Diagonalization never 'works' (produces a new or unique combination of set elements) in the finite world. And to produce aleph null in the first place we must turn to Zermelo where we are guaranteed a very basic, naive and the most axiomatic notion of infinity arrived at by process of....wait for it...iteration. Cantors diagonal argument is a wonderful bit of sophistry certainly. But it is not based on any real or even theoretically possibly constructable list. An infinite world of infinities is a semantic mobius strip.

  • @shiwanggupta8608
    @shiwanggupta8608 6 лет назад +2

    Great video..but there's a mistake in code.. you need to make two recursive calls in permuteUtil otherwise your code would print only one combination i.e. aabc

  • @kunjanshah_sr
    @kunjanshah_sr 4 года назад

    public class Permutations extends Activity {
    String TAG = Permutations.class.getSimpleName();
    char[] Res;
    int[] A;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String input="ABC";
    Res = new char[input.length()];
    A = new int[input.length()];
    perm("ABC".toCharArray(), 0);
    }
    void perm(char[] str, int k) {
    if (str.length == k) {
    Log.d(TAG, Arrays.toString(Res));
    } else {
    for (int i = 0; i

  • @karana2260
    @karana2260 4 года назад +1

    thanks for the awesome explanation. a suggestion in program:
    we can reduce num of lines in Hash map compute to:
    for (int k =0; k < input.length; k++) {
    countMap.put(input[k], occurence.getOrDefault(input[k], 0) + 1);
    }

  • @Sreejith1729
    @Sreejith1729 8 лет назад +1

    My first comment on youtube! This is a great effort and a very helpful one indeed! Thank you!

  • @SameerSrinivas
    @SameerSrinivas 7 лет назад +1

    Can anyone explain how the run time is O(n!) not by knowing the problem statement but just by looking at the code.

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

    But the time complexity is O(alphabet size ^ string length) since for each index we need to go through whole alphabet?

  • @ananthasubramanian7355
    @ananthasubramanian7355 5 лет назад +1

    You are amazing.. Thank you for this video !!!!

  • @malharjajoo7393
    @malharjajoo7393 6 лет назад +5

    Easy summary:
    1) when going into recursion, find leftmost non zero count.
    2) when coming out of recursive call, first move pointer 1 step ahead and then find first non zero count. :)

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

    i have been struggling to understand this,i can't tell u how glad I am to u I found this video.

  • @kaushalagarwal4153
    @kaushalagarwal4153 7 лет назад

    for code in c++:
    refer : ideone.com/5apaZ6
    problem link: leetcode.com/problems/permutations-ii/#/description

  • @bharatsreyus8748
    @bharatsreyus8748 5 лет назад

    can anyone give me code substitute for this program in c???? plllssss!

  • @andresaguilar3996
    @andresaguilar3996 5 лет назад

    My implementation in python: github.com/andresesfm/coding_challenges/blob/master/Tushar/test_string_permutations.py

  • @brucebigbro4079
    @brucebigbro4079 8 лет назад +1

    Dude, this video helps hell out of me, thanks!

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

    Leetcode Solution using this method in C++:
    pastebin.com/FM1Q2WKU

  • @SocajowaRS
    @SocajowaRS 4 года назад

    Phenomenal example here especially covering duplicates. Very helpful Tushar.

  • @abulfazalsaif1595
    @abulfazalsaif1595 5 лет назад +1

    use of count[i]++ in your code??

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

    sir ur pronunciation is good but now a days u r faking it a lot. its naturally good u need not do that

  • @dontknow6356
    @dontknow6356 4 года назад

    Thanks for the video.it's very helpful

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

    Thanks a lot. Amazing clarity in explanation :)

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

    How do we calculate the time complexity of this solution?

  • @whiteowl927
    @whiteowl927 4 года назад

    //C++ IMPLEMENTATION of the above concept
    #include
    using namespace std;
    string str="abcde";
    string out=str;
    void permute(int arr[],int l,int n,int x)
    { x++;
    if(l==n)
    { cout

  • @learnlearn236
    @learnlearn236 8 лет назад +1

    thank you so much to doing such type of videos really great work..thanks..thanks..thanks.!

  • @shadabshaikh5644
    @shadabshaikh5644 5 лет назад +1

    Best teacher :)

  • @AolaDIY
    @AolaDIY 4 года назад

    he is god sent!

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

    This look really messy... thank you though!

  • @mohitagarwal5070
    @mohitagarwal5070 4 года назад

    skip to 17:56 if you wanna skip whole permutations

  • @Rhythmswithruby
    @Rhythmswithruby 4 года назад

    Is this algorithm based on DFS? Characters are kind of marked as seen when their counts are at 0 and skipped. The result of a processed node is then pushed onto the recursion stack. I guess in this case though the count is reset to continue permuting. So maybe this Backtracking? Idk I'm new to these exhaustive algos.

  • @johnsmith-tc7nl
    @johnsmith-tc7nl 5 лет назад

    JavaScript Implementation
    function normalizeString(str) {
    let map = new Map();
    for (let char of str) {
    if (!map.has(char)) {
    map.set(char, 1);
    } else {
    map.set(char, map.get(char) + 1);
    }
    }
    let newStr = [...map.keys()].join("");
    return [newStr, map];
    }
    function permutations(str) {
    if (!str.length) {
    return null;
    }
    // remove dups and creaste count arr;
    let [newStr, countMap] = normalizeString(str);
    const results = [];
    const result = [];
    function backtrack(s, level) {
    for (let i = 0; i < s.length; i++) {
    let char = s.charAt(i);
    if (countMap.get(char) > 0) {
    countMap.set(char, countMap.get(char) - 1);
    result[level] = char;
    backtrack(s, level + 1);
    countMap.set(char, countMap.get(char) + 1);
    result[level] = null;
    }
    }
    // it will be called when for loop is finished that means all is 0
    if (level === str.length) {
    results.push([...result]);
    }
    }
    backtrack(newStr, 0);
    return results;
    }
    console.log(permutations("aabc"));

  • @marylin2850
    @marylin2850 8 лет назад

    Thanks for the video , nice explain.
    But I have a question on the code, should the 'result' pop back character after the recursive ?
    I used javascript to implement, if not pop back , the result is wrong. So I add 'result.pop()' after "count[i]++", then the result is right.

  • @044_karan9
    @044_karan9 4 года назад

    where can i find the c++ code for this problem

  • @mahesh_kok
    @mahesh_kok 6 лет назад

    Hi Modifications needs to be done . Your code cannot handle duplicates if any in array it gives arrayoutofbound exception ... Solution to it is While defining length of count[] and str[] it should be
    char str[] = new char[str.length];
    int count[]= new int[str.length];
    and not char str[] = new char[countmap.size()];
    and to print all the permutations in lexicographical order PASS the SORTED STRING

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

    Clear presentation, thank you!

  • @saravanasiva6476
    @saravanasiva6476 5 лет назад

    Brother i tell one programe please solve it to help me bro that programe is input =5,and string input is =5 output is aabbc, abbbc, aaabc, abbbc etc i dont know this programe pls help me bro

  • @embdlabs
    @embdlabs 8 лет назад

    Hello Tushar
    Thanks for all your great informative videos.
    Could you please share me the application name you used for coding in this video.
    This will really help me to teach my students.
    Vishal

  • @MainEffort
    @MainEffort 8 лет назад

    Hi Tushar, many thanks for your efforts. Would this be the same approach for integer arrays ? Could you do a video that considers integer array permutations ? Thanks.

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

    thiis man can be a good student not good teacher

  • @jayquilla1227
    @jayquilla1227 5 лет назад

    Shouldn't the last items in your result reset when you backtrack? Previous iteration uses a local variable that doesn't of what's on index 3 for example.

  • @anandratn8339
    @anandratn8339 8 лет назад

    I really appreciate your effort. Thank you for sharing knowledge. It's the best thing in the world. It would be great if you can share your view about some standard design pattern problem (How one should approach to solve the problem.) For Example, Pub-sub design pattern with concurrency which should be easy to scale for million of topic, messages, subscribers.

  • @avinashmv9686894578
    @avinashmv9686894578 5 лет назад

    I know you wouldn't read this comment , but still another great vid. Thanks Man!

  • @nofavors
    @nofavors 6 лет назад

    can you do the additive sequence problem? search for leetcode additive number string to see the problem link on google

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

    I am still not sure why the runtime would be big O of n factorial, can anyone explain please? thank you

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

      shouldn't the time complexity be O(m*n!), where m represents the length of the string without duplicates?

  • @arturdumchev3055
    @arturdumchev3055 4 года назад

    You could use Syster.out.println(Arrays.toString(result));

  • @chandrashekar-pb8ym
    @chandrashekar-pb8ym 8 лет назад

    In this case, The counts determine the how many times we can use the character there by eliminating the dups in the output.
    the character counts along with stack level which controls the result table will decide the permutation. The first for loop will ensure the order of the output. Just sharing my understanding

  • @rudreshdixit8368
    @rudreshdixit8368 4 года назад

    thanks sir. your videos are very insightful and explain every aspect of the problem statement

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

    Finally understood how to go about a backtracking tree. Very helpful thank you!

  • @mahesh_kok
    @mahesh_kok 6 лет назад

    Bhai tu hai kaun, Kaha sey aaya hai, , what an awesome stuff to start the permutaion and combination of strings.bro u killed it....cant find any better explanation than yours to simple looking complex implementation of this problem.. cheers to u yarr

  • @rahuljaiswal4409
    @rahuljaiswal4409 6 лет назад

    If ,we are asked to print Permutation taking r at a time, then can we change the printing condition form (level ==result.length) to (level==r) ??.

  • @prashanthc3715
    @prashanthc3715 5 лет назад +1

    please explain, when level=result.length, where exactly the Control RETURNS to?
    not able to understand the return call here.

    • @dracomalfoy1245
      @dracomalfoy1245 5 лет назад

      to the upper level of recursion tree. each time recursion is called u go a level deeper into the tree. so when u return to go a level higher .....

  • @ErfanHossainShoaib
    @ErfanHossainShoaib 8 лет назад

    I am searching a good algorithm for permutation from last 2 years but I found noting good. But at last I find a good way from here. Your lectures are awesome.

  • @dearvivekkumar
    @dearvivekkumar 8 лет назад +1

    Guy ... Your effort is highly apreciated

  • @nightbemine
    @nightbemine 7 лет назад

    Hi Tushar,
    Your technique and explanation is very good and thoughtful.
    I just have one concern here that the explanation and the code part does not go hand in hand. In explanation you said the algo does not give duplicates but in the code you said it will give duplicates. Can you please provide the code as per the explanation.
    Thanks

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

    great explanation tushar _/\_

  • @chandreshvashistha
    @chandreshvashistha 8 лет назад +1

    Hi Tushar, I believe, this is not an efficient solution in terms of running time. Any thoughts?

    • @chandreshvashistha
      @chandreshvashistha 8 лет назад

      First of all, thanks for your reply.. :)
      I am new to DSA so please correct me if my understanding is wrong. I tried running the program for the following input and it takes noticeable time to complete execution.
      252, 632, 262, 707, 506, 701, 475, 410, 696, 631, 903, 516, 149, 344, 101, 42, 891, 991, 555, 652
      I believe that running time is O(n!) and with this understanding I was wondering that if there is a better solution.

  • @songhaoli304
    @songhaoli304 4 года назад

    well explained and well-illustrated. Though the theory part at 2:00 was a bit hard to digest.

  • @d.sathwik5290
    @d.sathwik5290 3 года назад

    what is the prerequisite algorithm should be learnt before doing this problem

  • @rafael246
    @rafael246 4 года назад

    Awesome!
    I have a question in the python code. How can I store these values in a variable?
    Whichever way I try to append the result to a list, it always ends up appending only the last term, not all of them.

  • @carloslaguna7036
    @carloslaguna7036 8 лет назад

    Where do you get all your algorithms? Do you use a text book or any other source?

  • @Venkat2811
    @Venkat2811 8 лет назад

    Nice Video Tushar. You videos always increase the level of my understanding. Thanks :)

  • @rayhaanbhikha9094
    @rayhaanbhikha9094 4 года назад

    Anyone know what the algorithm is actually called?

  • @malharjajoo7393
    @malharjajoo7393 7 лет назад

    This is exactly how this should be explained.
    Although it could have helped if you explain what happens if we dont use a count for the repeated elements.
    In the case we don't , the permutations are repeated.

  • @Surajkumar-pp6co
    @Surajkumar-pp6co 6 лет назад

    thank you! earlier i was reading this code in quora and i could not understand what the author was doing .. but now through your visuals i understood it better and completely. Thanks again;