But it doesn't have to end here! Sign up for the 7-day coding interview crash course and you'll get a free Interview Cake problem every week.
Write a recursive function for generating all permutations of an input string. Return them as a set.
Don't worry about time or space complexity—if we wanted efficiency we'd write an iterative version.
To start, assume every character in the input string is unique.
Your function can have loops—it just needs to also be recursive.
Make sure you have a base case! Otherwise your function may never terminate!
Let's break the problem into subproblems. How could we re-phrase the problem of getting all permutations for "cats" in terms of a smaller but similar subproblem?
Let's make our subproblem be getting all permutations for all characters except the last one. If we had all permutations for "cat," how could we use that to generate all permutations for "cats"?
We could put the "s" in each possible position for each possible permutation of "cat"!
These are our permutations of "cat":
For each of them, we add "s" in each possible position. So for "cat":
And for "cta":
And so on.
Now that we can break the problem into subproblems, we just need a base case and we have a recursive algorithm!
If we're making all permutations for "cat," we take all permutations for "ca" and then put "t" in each possible position in each of those permutations. We use this approach recursively:
How does the problem change if the string can have duplicate characters?
What if we wanted to bring down the time and/or space costs?
This is one where playing with a sample input is huge. Sometimes it helps to think of algorithm design as a two-part process: first figure out how you would solve the problem "by hand," as though the input was a stack of paper on a desk in front of you. Then translate that process into code.
Powered by qualified.io