Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a recursive method that returns all permutations of a String with distinct characters, then explain its time complexity and how deep the recursion goes for a 10-character input.

A recursive permutation method picks each character in turn as the first character and prepends it to every permutation of the remaining characters, with the empty string as the base case. A string of n distinct characters has n! permutations and each takes O(n) work to build, so the time is O(n * n!): 3,628,800 results for 10 characters. The recursion is only n levels deep, so the stack is never the problem; the memory for the result list is.

Why this question is asked

Permutations are the classic exercise for recursion because the problem has a natural self-similar shape: a permutation of "abc" is one letter followed by a permutation of the other two. Interviewers use it to check that we can find a base case, write the recursive step cleanly, and then reason about cost, which grows faster than almost anything else we meet in daily work. In this answer, we will recap how recursion breaks the problem down, write a simple version, trace it on a small input, write a faster backtracking version, and then work out the time, the recursion depth and the memory for 10 characters.

1A Quick Recap of How Recursion Splits This Problem

A recursive method solves a problem by calling itself on a smaller version of the same problem. It needs two parts: a base case that can be answered directly, and a recursive case that reduces the problem and combines the results.

For permutations, the reduction is natural. To list every ordering of "abc", we choose which character goes first. If it is 'a', the rest is every ordering of "bc"; if it is 'b', the rest is every ordering of "ac"; and so on. Each choice leaves a string one character shorter, so eventually we reach a string of length 0 or 1, whose only permutation is itself. That is the base case.

2Writing the Simple Recursive Version

The first version follows that description directly. For each index i, it takes the character at i, recurses on the string without it, and prefixes the character to every result.

Java
static List<String> permutations(String s) {
if (s.length() <= 1) {
return List.of(s); // base case: "" or one character
}
List<String> result = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
String rest = s.substring(0, i) + s.substring(i + 1);
for (String p : permutations(rest)) {
result.add(c + p);
}
}
return result;
}
permutations("abc"); // [abc, acb, bac, bca, cab, cba]
permutations(""); // [""]: one empty string, printed as []
permutations("abcd").size(); // 24

Notice that the base case covers both the empty string and a single character. Returning List.of(s) for the empty string means there is exactly one way to arrange nothing, which keeps the arithmetic correct: 0! is 1.

3Tracing the Calls for "abc"

It helps to follow the calls once. The top call tries 'a' first, so it calls permutations("bc"). That call tries 'b' and recurses on "c", which is a base case and returns ["c"], giving "bc". It then tries 'c', recurses on "b", and gets "cb". So permutations("bc") returns ["bc", "cb"], and the top call prefixes 'a' to get "abc" and "acb". The same happens with 'b' first and with 'c' first.

Step throughThe call tree for permutations("abc"), first branch
  1. permutations("abc")tries a, b, c in turn
  2. pick 'a' -> permutations("bc")tries b, then c
  3. pick 'b' -> permutations("c")base case returns [c]
  4. Combine"bc", then "cb" from the other branch
  5. Prefix 'a'"abc", "acb"
  6. Repeat for 'b' and 'c' first6 results in total

6 steps in order. Play them, or step through them one at a time.

So the calls form a tree. The root has 3 children, each of those has 2, and each of those has 1. The number of leaves is 3 x 2 x 1 = 6, which is 3!, one leaf per permutation. The depth of the tree is 3, one level per character.

4A Faster Version With Backtracking

The simple version creates a lot of short-lived strings: every call builds a new rest string with substring, and every level builds new result strings by concatenation. Backtracking avoids this. We keep one char[] and swap characters in place: to choose the character for position k, we swap each remaining character into position k, recurse on position k + 1, and swap back afterwards, which is the "backtrack" step that restores the array for the next choice.

Java
static List<String> permutationsFast(String s) {
List<String> out = new ArrayList<>();
permute(s.toCharArray(), 0, out);
return out;
}
private static void permute(char[] a, int k, List<String> out) {
if (k == a.length) {
out.add(new String(a)); // one finished permutation
return;
}
for (int i = k; i < a.length; i++) {
swap(a, k, i); // choose a[i] for position k
permute(a, k + 1, out);
swap(a, k, i); // undo the choice
}
}
private static void swap(char[] a, int i, int j) { char t = a[i]; a[i] = a[j]; a[j] = t; }
permutationsFast("abc"); // [abc, acb, bac, bca, cba, cab]

Notice the order is slightly different (cba comes before cab), because swapping changes which characters remain. Both lists contain the same six permutations. The only string we create is the finished result at each leaf.

5Time Complexity, Depth and Memory for 10 Characters

A string of n distinct characters has n! permutations, because there are n choices for the first position, n - 1 for the second, and so on. Building each permutation costs O(n), since we create a string of n characters. So the total work is O(n * n!), and no algorithm that returns every permutation can do better, because the output alone has n * n! characters.

For 10 characters, 10! is 3,628,800 permutations. The recursion depth, however, is only n: at most 11 frames on the stack for the backtracking version (positions 0 to 10). A Java thread's stack holds thousands of frames, so depth is not a concern here. Memory is. Each result is a String of 10 characters: with compact strings, about 24 bytes for the String object and about 32 bytes for its byte array, so roughly 56 bytes, plus a 4-byte slot in the ArrayList. That is about 3.6 million x 60 bytes, around 220 MB, which is enough to cause an OutOfMemoryError on a small heap.

For 12 characters, 12! is 479 million, which no list can hold. When n is that large, we should not collect results at all. We pass a Consumer<String> and process each permutation as it is produced, so memory stays at O(n).

How fast n! grows
nPermutations (n!)Approx. list memory
36a few hundred bytes
840,320about 2 MB
103,628,800about 220 MB
12479,001,600about 29 GB, will not fit
The stack depth is only n + 1 in every row; the output is what explodes.

6Follow-up questions

How would you handle duplicate characters?

With duplicates, such as "aab", the methods above produce repeated results: 6 strings but only 3 distinct ones. Collecting into a Set works but still does all the work. A better way is to sort the characters and, at each position, skip a character if it is the same as one already tried at that position. In the swap version, we keep a small Set<Character> per level and skip any character we have already placed at position k. Then "aab" produces exactly aab, aba and baa, and the number of results is n! divided by the factorials of each character's count.

Can you generate the next permutation without recursion?

Yes. The classic next-permutation algorithm finds the rightmost position where a character is smaller than the one after it, swaps it with the smallest larger character to its right, and reverses the tail. Starting from sorted order and repeating gives every permutation in lexicographic order with O(1) extra memory and no recursion.

Why not return a Stream instead of a List?

A lazily generated stream, or a Consumer callback, lets the caller process each permutation and discard it, so memory stays small even when n! is huge. It is the right shape when the caller only needs to test each permutation, for example searching for one that satisfies a rule.

7Conclusion

In this answer, we wrote a recursive permutation method with the empty or one-character string as the base case and a loop that fixes each character in front of the permutations of the rest. We traced its call tree, which has n! leaves and depth n, and wrote a backtracking version that swaps characters in place to avoid creating substrings. The time is O(n * n!), so 10 characters give 3,628,800 results; the stack only goes about 10 levels deep, and the real risk is the memory of the result list.

What to say in the interviewAbout 90 seconds aloud

Open with

The idea is that a permutation is one character followed by a permutation of the rest. So my base case is a string of length zero or one, which returns a list containing just that string.

Then, if they want more

In the recursive case I loop over each index, take that character, recurse on the string without it, and prepend the character to every result.

That version is easy to read, but it creates a lot of substrings, so I would usually write the backtracking version: one char array, and for each position k I swap each remaining character into k, recurse on k plus one, and swap back. At the leaf I add new String of the array to the output.

For complexity, there are n factorial permutations and building each costs O(n), so it is O(n times n factorial), and that is optimal because the output itself is that big. For 10 characters that is 3,628,800 strings.

The recursion depth is only n, about 10 frames, so stack overflow is not a concern; the problem is memory, roughly 200 MB for the list. For larger n I would pass a consumer and process each permutation as it is generated instead of collecting them. With duplicate characters I would skip characters already tried at the same position.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Write a recursive method that returns all permutations of a String with distinct...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/20f617422e/