Quick revision
The short answer
Listing every permutation of a string is a backtracking problem. We fill one position at a time: try each unused character, mark it and append it, recurse for the next position, then remove it and unmark it, recording the path when it is full. Sorting first and skipping a character equal to an unused twin removes repeated arrangements. There are n! permutations, so it takes O(n * n!) time and O(n) extra space besides the output.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Every sequence of positions, then filter | O(n * n^n) | a set of all results |
| Backtracking with a used array | O(n * n!) | O(n) besides the output |
What to remember
We listed every permutation of a string by filling one slot at a time: choose an unused letter, explore the remaining slots with the same method, then unchoose it so the next letter can take that slot. Sorting first and skipping a letter whose equal twin is unused removes repeated strings. There are n! answers, so the time is O(n * n!) and the extra space O(n). The clue to remember is the word every applied to arrangements built by a sequence of choices: build the answer choice by choice, refuse a bad choice at once, and undo each choice before trying the next.
1What a permutation is, told with chairs for a photograph
Imagine three friends, Asha, Ben and Chen, about to be photographed sitting on three chairs in a row. How many different photos can they make? For the first chair you may seat any of the three. Once someone sits there, two people remain for the second chair, and then one person for the last. Each different seating is one permutation, and listing every seating is exactly what this question asks, with letters instead of friends.
A permutation of a string is an arrangement of all its characters in some order, each character used exactly once. For "abc" there are six: abc, acb, bac, bca, cab and cba. We must produce every one of them. The question says print; our method returns them in a list, which main then prints, because a list is also easy to test.
Let us do it on paper the way we seated the friends. Put a in the first slot; b and c can follow as bc or cb, giving abc and acb. Put b first for bac and bca, then c first for cab and cba. Fixing the first letter leaves the same problem on fewer letters.
The count follows the same reasoning. There are 3 choices for the first slot, 2 for the second and 1 for the last, so 3 times 2 times 1, which is 6. That product is called n factorial and written n!. It grows terribly fast: 10 letters already have 3,628,800 permutations.
Each row is one permutation of "abc". The first letter is marked; each first letter is followed by both arrangements of the other two.
1The six permutations of "abc" in sorted order. Rows come in pairs that share their first letter, which is how we will build them.
What to assume
- Print or return?
- We return a
List<String>, which main prints. - In what order?
- Sorted order.
- Can letters repeat, and should a repeated arrangement appear once?
- We assume yes, so "aab" gives aab, aba and baa, three strings, not six. The empty string has exactly one permutation, the empty string itself.
Many people find this question frightening because recursion and undoing choices sound abstract. The problem is smaller than it looks. The whole solution is the chair game: seat someone, fill the remaining chairs, then ask that person to stand up so someone else can sit there.
A careful candidate asks a few questions first. Print or return? We return a List<String>, which main prints. In what order? Sorted order, which we get for free by sorting the letters first. Can letters repeat, and should a repeated arrangement appear once? We assume yes, so "aab" gives aab, aba and baa, three strings, not six. The empty string has exactly one permutation, the empty string itself.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a backtracking problem
When a beginner reads this question, a common first instinct is nested loops: one loop for the first letter, one inside it for the second, one for the third. That works for exactly three letters, but the number of loops would have to change with the length of the string, and Java cannot write a different number of loops for each input. So we need a way to make choices whose number depends on the input.
The first clue is the word every. We must list every arrangement, not count them or find the best one. When all possible answers must be produced, there is no shortcut around visiting each one, so the question is how to visit them all without missing any and without wasted work.
The second clue is that each answer is built by a sequence of choices: a letter for slot 1, then a letter for slot 2, and so on, with each choice limiting the next ones, since a used letter cannot be used again. A problem whose answers are sequences of choices like this can be pictured as a tree of choices, where each branch is one choice and each path from the top to the bottom is one complete answer.
Together the clues point to the backtracking pattern. Backtracking means walking that tree of choices with recursion: make one choice, solve the rest by calling the same method, then undo the choice and try the next one. The undo step is what gives the pattern its name, because we go back along the track we came by, like retracing your steps in a maze to try the next turning. The rhythm is often called choose, explore, unchoose.
The general rule to carry away is this. When a question asks for all combinations, subsets or arrangements, or for any arrangement that obeys rules, as in Sudoku or N-queens, build the answer one choice at a time, check each choice is allowed at the moment you make it, recurse for the rest, and undo the choice before trying the next.
Some patterns look similar but do not fit. Dynamic programming also deals with choices, but it suits questions that ask for a count or a best value, where answers to smaller problems can be reused. Here we must list every answer, so nothing can be merged.
3The honest first attempt, every sequence of positions
One brute force avoids thinking about choices at all. Treat each slot as able to hold any position of the string, 0, 1 or 2, so every sequence of positions is like a number written with n digits in base n. Count through all of them, n^n in total, build the string for each, and keep only those that used every position exactly once. A sorted set removes duplicates when letters repeat. It is honest, correct and mechanical, a reasonable first thing to try.
Let us count it by hand for "abc". There are 3^3 = 27 sequences of positions, from 0 0 0 to 2 2 2. Only 6 of them, such as 0 1 2 for abc and 2 1 0 for cba, use each position once; the other 21, such as 0 0 1, are thrown away. So more than three quarters of the work is wasted, even for three letters.
It gets much worse. For 8 letters there are 8^8, about 16.7 million sequences, of which only 40,320 are permutations. Each sequence costs about n steps, so the time is O(n * n^n), read as order n times n to the power n, far more than the n! answers we need.
So where is the waste? Look at the sequence 0 0 1. It went wrong at its second digit, the moment it used position 0 twice, yet the brute force went on building the whole string before rejecting it. And every other sequence starting 0 0 was built and rejected the same way. So let us ask the question that leads further. If we refuse a used letter at the very moment we are about to choose it, can we avoid building any wrong sequence at all?
4Getting to backtracking, one observation at a time
Go back to the chairs. We fill slots from left to right. For the current slot we may choose any letter not yet used. Once we choose one, the remaining slots must be filled with the remaining letters, which is the same problem one letter smaller. So one method can handle every slot by calling itself for the next one.
We need two pieces of memory. A StringBuilder called path holds the letters placed so far, like the people already seated. A boolean array called used, one entry per letter of the input, marks which letters are already in the path, like a list of who is sitting down. When path is as long as the input, every slot is filled, so we record a copy of it.
For each slot the method loops over all the letters. For each unused letter it chooses it, by setting used[i] to true and appending it to path; it explores, by calling itself to fill the next slot; and then it unchooses, by removing the last letter from path and setting used[i] back to false.
The sorted letters a, a, b. The second a may be chosen only when the first a is already in the path.
- path
- "aa"
- slots filled
- 2 of 3
- recorded
- none yet
1On the sorted letters a, a, b, the path takes the first a, then the second a. That is allowed, because its twin, the first a, is already in the path.
- path
- ""
- slots filled
- 0 of 3
- recorded
- aab aba
2The rhythm records "aab" and then "aba", and undoes everything. The path is empty again, ready for a new first letter.
- path
- ""
- slots filled
- 0 of 3
- recorded
- aab aba
3For slot 1 the loop reaches the second a. Its twin, the first a, is not in the path, so we skip it, since it would repeat "aab" and "aba".
- path
- "baa"
- slots filled
- 3 of 3
- recorded
- aab aba baa
4The loop chooses b instead, then the two a letters in order, and records "baa". Three distinct strings, each exactly once.
Now comes the question every beginner asks. Why do we need the unchoose step at all? Let us leave it out and see what we lose. After recording abc, we return to the slot 3 loop, then to slot 2. Without undoing, path still says "abc" and all three letters are still marked used. The slot 2 loop moves on to c, but c is marked used, so it is skipped, and nothing more is ever found. The unchoose step puts things back exactly as they were before the choice, like asking the person to stand up so the chair is free for the next person.
Repeated letters need one more rule, shown in the picture above. With "aab", the two a letters are different positions but look the same, so choosing the first a or the second a for slot 1 leads to identical strings. We sort the letters first so equal ones sit side by side, then skip a letter if it equals the one before it and that earlier twin is not in the path. This forces equal letters to be used in their original order, the second a only after the first, so each distinct string is built once.
Why is the method correct? Every permutation is one choice of letter per slot, and at each slot the loop tries every unused letter in turn. So every permutation is reached along exactly one path of choices, and nothing is built twice. Wrong sequences like 0 0 1 are never started, because a used letter is refused at the moment of choosing.
The mistake beginners make most often is undoing only half the choice, removing the letter from path but leaving used[i] true. Nothing crashes; the method quietly returns only [abc], because every letter stays marked as used.
5Watching choose, explore and unchoose on "abc"
The picture plays the method on "abc", using the paths the Java method produced. The three cells are the sorted letters. A letter marked as done is used in the current path, the letter just chosen is marked as now, and the letter that completes a permutation is marked as found. The panel shows path, how many slots are filled and every permutation recorded so far.
The first branch, everything that starts with a, is shown one choice at a time. After that, each frame shows a whole permutation being recorded, so you can see the rhythm repeat.
Letters marked as done are in the current path. The first branch is shown choice by choice; later frames each show one more permutation recorded.
- path
- ""
- slots filled
- 0 of 3
- recorded
- none yet
1We start with an empty path, no letter used and nothing recorded. The first slot can take any of a, b or c.
- path
- "a"
- slots filled
- 1 of 3
- recorded
- none yet
2The loop for slot 1 tries i = 0 first. a is unused, so we choose it: mark a as used and append it, making the path "a".
- path
- "ab"
- slots filled
- 2 of 3
- recorded
- none yet
3We recurse to fill slot 2. a is used, so the loop skips it and chooses b. The path is "ab".
- path
- "abc"
- slots filled
- 3 of 3
- recorded
- abc
4For slot 3 only c is left, so we choose it. The path "abc" is full, so we record it and return.
- path
- "a"
- slots filled
- 1 of 3
- recorded
- abc
5We undo c, then undo b: each is removed from the path and marked unused again. We are back at "a", with slot 2 to fill differently.
- path
- "ac"
- slots filled
- 2 of 3
- recorded
- abc
6The slot 2 loop moves on to i = 2 and chooses c. The path is "ac", and b is free again for slot 3.
- path
- "acb"
- slots filled
- 3 of 3
- recorded
- abc acb
7Slot 3 takes the only free letter, b. The path "acb" is full, so it is recorded as the second permutation.
- path
- ""
- slots filled
- 0 of 3
- recorded
- abc acb
8Every choice under a is used up, so we undo b, c and finally a. The path is empty again, and the slot 1 loop moves to i = 1.
- path
- "bac"
- slots filled
- 3 of 3
- recorded
- abc acb bac
9With b in slot 1, the same rhythm chooses a and then c, and records "bac". Notice a is used again, because undo made it free.
- path
- "bca"
- slots filled
- 3 of 3
- recorded
- abc acb bac bca
10We undo c and a, choose c for slot 2 and a for slot 3, and record "bca". Both arrangements that start with b are done.
- path
- "cab"
- slots filled
- 3 of 3
- recorded
- abc acb bac bca cab
11After undoing back to the empty path, the slot 1 loop chooses c, and the rhythm gives "cab".
- path
- ""
- slots filled
- 0 of 3
- recorded
- abc acb bac bca cab cba
12Finally "cba" is recorded, every choice is undone, and the loop for slot 1 ends. All six permutations are in the list, in sorted order.
Let us read the important frames back. In the first three frames path grows from "a" to "ab" to "abc", one choice per slot, and the full path is recorded. Then comes the frame that matters most: c and b are undone, path is back to "a", and b and c are free again. Only because of that can the slot 2 loop choose c and build "acb".
When everything under a is used up, a itself is undone and the path is empty. The slot 1 loop then tries b, and the same rhythm produces "bac" and "bca", then "cab" and "cba" under c. Because the letters were sorted and each loop tries them from left to right, the six permutations come out in sorted order.
In all, the method chose a letter 15 times, recorded 6 complete paths and undid 15 choices, and it never built a wrong sequence, against the 27 sequences of the brute force.
6The complete Java program
Here is the full program. The public method sorts the letters and starts the recursion, and the private build method does the choose, explore and unchoose loop. main prints the permutations of "abc" and "aab", counts them for the empty string and for "abcd", and prints those of "aaa", and each comment shows what that line prints.
Let us read it in the order it runs. permutations turns the string into a char array and sorts it, so equal letters become neighbours and the output comes out in order. It then calls build with a fresh used array, an empty path and an empty output list.
build first checks whether the path is full. If it is, it adds path.toString(), a fresh copy, to the list and returns; this is the base case that stops the recursion. Otherwise the loop tries each index i. A used letter is skipped with continue. A letter equal to the one before it, whose earlier twin is not used, is skipped too, which is the duplicate rule.
For any other letter the four lines are the rhythm we worked out. used[i] = true and path.append(chars[i]) make the choice, build(...) explores the rest, and path.deleteCharAt(path.length() - 1) and used[i] = false undo it in reverse order. Then the loop moves on to the next letter for the same slot.
So main prints [abc, acb, bac, bca, cab, cba], then [aab, aba, baa]. The empty string gives 1, because the empty path is already full. "abcd" gives 24, which is 4!, and "aaa" gives just [aaa], because the skip rule allows the three a letters only in their original order.
7How much it costs, and the cases at the edges
Let us count on the example first. For "abc" the method made 16 calls, 1 for the empty path, 3 with one letter, 6 with two and 6 with three, and recorded 6 strings of length 3. In general there are n! complete permutations, and copying each into a String costs n steps, so the output alone needs O(n * n!) time. The partial paths add at most a small constant factor, so the total time is O(n * n!).
Besides the output, the method keeps the path, the used array and one waiting call per filled slot, so the extra space is O(n). The output itself holds n! strings of n characters, which for long strings is the real limit.
| Approach | Time | Extra space |
|---|---|---|
| Every sequence of positions, then filter | O(n * n^n) | a set of all results |
| Backtracking with a used array | O(n * n!) | O(n) besides the output |
The edge cases need no special code. The empty string reaches the base case at once and returns one empty permutation. A single letter returns itself. Repeated letters are handled by the sort and the skip rule, down to a string of one repeated letter, which returns a single string.
Because the output grows like n!, no method can be fast for long strings: 12 letters already give 479 million permutations. For anything beyond about 10 letters, printing each permutation as it is found, rather than collecting them all in a list, is the only practical choice, and the build method can be changed to do that in one line.
8Follow-up questions
What is the swap-based version?
Instead of a path and a used array, we work on the char array itself. To fill position k, we swap each index i from k to n - 1 into position k, recurse on k + 1, and then swap back to undo. When k reaches n, the array holds one permutation. It needs no boolean array, but its output is not in sorted order, and skipping repeated letters needs a small set of letters already tried at each position, because sorting does not survive the swaps.
How do you find the next permutation without generating all of them?
Read the array from the right and find the first index i where a[i] is smaller than a[i + 1]; if there is none, the array is already the last permutation. Then find the rightmost j with a[j] larger than a[i], swap the two, and reverse everything after i. For acb, i is at a, j is at b, the swap gives bca, and reversing after b gives bac, the next one in sorted order. It takes O(n) time and O(1) space.
How would you count the distinct permutations without listing them?
We divide n! by the factorial of each letter's count, because swapping identical letters gives the same string. For "aab" that is 3! divided by 2!, which is 3, matching the list. For "mississippi" it is 11! divided by 4! for the i letters, 4! for the s letters and 2! for the p letters, which is 34,650. This uses no backtracking at all, because we only need the number.
9Conclusion
We listed every permutation of a string by filling one slot at a time: choose an unused letter, explore the remaining slots with the same method, then unchoose it so the next letter can take that slot. Sorting first and skipping a letter whose equal twin is unused removes repeated strings. There are n! answers, so the time is O(n * n!) and the extra space O(n). The clue to remember is the word every applied to arrangements built by a sequence of choices: build the answer choice by choice, refuse a bad choice at once, and undo each choice before trying the next.
Open with
Let me check the requirements first. I return all permutations as a list, in sorted order, and if letters repeat I list each distinct string once, so aab gives three strings.
Then, if they want more
The empty string gives one empty permutation. A brute force could count through every sequence of positions, n to the power n of them, and filter out the ones that reuse a position, but almost all of that work is thrown away. Since we must produce every arrangement and each one is a sequence of choices, I will use backtracking.
I sort the characters, then recurse with a StringBuilder path and a boolean used array. If the path is full, I add a copy to the result. Otherwise, for each index that is not used, I mark it, append its character, recurse, then delete the character and unmark it, so the next character can take that position.
To avoid duplicates I skip a character when it equals the previous one and the previous one is not used, which forces equal letters into their original order. There are n factorial permutations and each costs O(n) to copy, so the time is O(n times n factorial), and the extra space is O(n) besides the output.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 35 times in that collection. How it is counted
- Official documentation
- StringBuilder (Java 21), Arrays (Java 21), ArrayList (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Print every permutation of the characters in a string.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-every-permutation-of-the-characters-in-a-string-ce1881/
Coding patterns, question 14 of 15 Back to the path
More backtracking questions