How to generate all permutations of an array or string? This is quite the popular question in interviews… In fact, I personally got asked to generate all permutations of an array or string in 3 interviews last year. Therefore it is essential that if you are planning to go through interviews, you have a complete understanding of this question ready at your fingertips.

First of all to open up the topic, if you have forgotten those hard earned Calculus A+ when you were a freshman, here are a few helpful resources, Permutation on Wikipedia , Permutation on RegentPrep and Permutation on MathWorld to help you create a comprehensive view of the question at hand.

I personally like the second article much better, as it is smaller and much more concise. The initial line says it all:

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself.

Does not sound too hard, does it? So let us think about how to solve this problem. First of all as we always do, we have to discuss constraints and requirements. The number of outputs will be vastly large. Let’s take a look at an example of an array / string of 4 items:

As you can see the number of outputs is quite big, namely **O(n!)** time complexity (24 = 4*3*2*1). Do we want to hold all that data in memory? Probably not. We should suggest in our interview that it would be better if we assume that it’s ok to just print out the output. That should lessen the memory load, no? Let us see!

At first sight it seems like it would be easy to implement an answer to generate all permutations of an array or string, using recursion, since you can imagine how solving a subset of the problem (solving a permutation of 3 items in the above example), will greatly help in solving the permutation of 4 items.

## How to Generate All Permutations of an Array or String – Basic Algorithm

- For each item in the array: Get the item, and append to it the permutation of the remaining elements
- The base case: The permutation of a single item – is itself.

As you can see it sounds pretty easy!! So let us just get our hands to it and try to program a solution that will generate all permutations of an array or string in PHP.

## How to Generate All Permutations of an Array or String in PHP

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public function findPermutations($myArray) { findPermutaitonsHelper($myArray, []); } public function findPermutationsHelper($itemArray, $permArray) { if (count($itemArray) == 1) { $permArray[] = $itemArray[0]; print_r($permArray); return; } for ($i = 0; $i < count($itemArray); $i++) { $item = $itemArray[$i]; // Change the arrays for the permutation. unset($itemArray($i)); $permArray[] = $item; findPermutationsHelper($itemArray, $permArray); // Reset arrays back to initial state. array_pop($permArray); $itemArray[$i] = $item; } } |

Well it took me a bit longer to write but it worked out at the end. To be noted is that since we are using PHP we can use a wonderful feature of the language which passes objects by value, rather than reference (unless otherwise noted), so in this case we can ignore the fact that our arrays are being changed in inside functions, since to the callee, they will seem unchanged :). So how would we find all permutations of an array or string in a language that passes arguments by reference such as Java or C++? Well the idea is that we would have to deep copy the passed array, so let us see how that would work.

Assumption – There are no negative items in the permutation array.

## How to Generate All Permutations of an Array or String in Java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class JavaPermutations { public void printPermutations(ArrayList<Integer> myList) { ArrayList<Integer> permList = new ArrayList<Integer>(); JavaPermutations.printPermutaitonsHelper(myList, []); } public void printPermutationsHelper(ArrayList<Integer> itemList, ArrayList<Integer> permList) { if (itemArray.length == 1) { System.out.println("" + itemArray[0]); return; } for (int i = 0; i < itemArray.length; i++) { int item = itemArray[i]; // Change the arrays for the permutation. itemList.set(i, -1); permList.add(item); JavaPermutations.printPermutationsHelper(itemList, permList); // Reset arrays back to initial state. itemList.set(i, item); permList.remove(i); } } } |

As you can see it seems very similar, with a few tweaks per the language. In fact we did not have to deep copy the array / list / string, because we are always setting it back to the original form.

This was a first post on How to Generate All Permutations of an Array or String in Java and PHP. Most likely if you can write this out and mention the reference and value argument pointers for the language of your choice, you will do just fine in your interview. However there are a few caveats. While we analyzed the time complexity from the beginning, we did not say anything about the space complexity of our solution. As it turns out, we are using about O(N!) space too, since we are keeping haggling arrays in our stack. This might be a bottleneck, but the solution needs a trickier algorithm which is generally not required to do well in this “How to Generate All Permutations of an Array” interview question, but which could make you look like a superstar. Given it’s complexity we will take a look at that solution in a part II of this post.

Hope you guys enjoyed it! And I’ll see you guys next time ;D

#### Latest posts by Ajk (see all)

- Find Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017

I’ve seen a lot of solutions about the permutation problem online and none was as clear and as concise as this. Waiting for part 2!