In this problem, our base case is a permutation of empty String, which is nothing but the empty String itself. If you don't have a base case then your program will eventually terminate with. In the case of recursion, the most important question is the base case, because that is responsible for stopping recursive calls. So, this solution uses both for loop and recursion to print all permutations of a given String. This is where for loop comes into the picture. In order to calculate all permutations of a String, you need to repeat this exercise for all characters one at a time. in the case of "xyz", you can fix "x" and calculate permutation of "yz". permutation of n characters is nothing but fixing one character and calculating permutation of n - 1 characters e.g. Similarly, permutations are also a recursive problem e.g. factorial of n is nothing but n * factorial of n -1. If you remember the factorial problem you know that factorial is naturally recursive i.e. for a String of 3 characters like "xyz" has 6 possible permutations, xyz, xzy, yxz, yzx, zxy, zyx as seen in our example. Similarly for a String of n characters there are !n (factorial of n) permutations are possible e.g. if you have String "ab" then it will have just 2 permutations "ab" and "ba", because the position of the character in both Strings is different. Now let's get back to the problem, Permutation refers to the ordering of characters but it takes position into account i.e. Solution 1 - Final All Permutations of given String Using Recursion and Loop Since recursion is a tricky programming concept to master, it's not easy for every programmer to solve this problem on the fly, especially if you are not coding on a daily basis or don't have that highly sought-after code sense. There are two main ways to solve this problem, using loops or by using recursion, the second one is what the interviewer expects. Depending upon the company you are going for an interview, they may ask you to code on IDE like Eclipse or NetBeans, or simply write code in plain paper, so be prepared for both. Typically, you will be asked to write a method, which accepts a String and print all permutations or may return all permutations in a List for a junior developer position. It does not only serve as a good question to check whether the candidate understands recursion but also its one of the better java programming exercise for beginners. Since then I have seen this question many times at various written tests and Java interviews for a junior developer position. I have first seen this question in my college exam when we were asked to code the solution using C or C++ language. How to find all permutations of a String using recursion is one of the tricky coding questions from programming job interviews.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |