Amazon Interview Question

Print out all the permutations of a string.

Interview Answers

Anonymous

Oct 20, 2009

My favorite approach is to use a bitvector. As the best-case complexity is O(n*2^n), it not feasible to permute a large N. An integer (32-bits) or long (64-bits) is good enough. Each bit acts as a flag of whether the character can be shown. Increment and show until the end-point is reached. For example, "abc" has the permutation of: 000 --> ___ 001 --> __c 010 --> _b_ 011 --> _bc 100 --> a__ 101 --> a_c 110 --> ab_ 111 --> abc The code is very simple and lazily evaluated, so it has O(1) space complexity. A gray code counter could be used to have a cleaner output, but that's a nit.

1

Anonymous

Dec 5, 2010

The answer given by Ben is wrong, as it is not printing a permutation of the string. For example, given abc, the permutation of abc will result in abc acb bca bac cab cba The complexity of the algorithm described below is (n!) as the permutation of any string will result in printing the string n! times. First of all, an example to illustrate the algorithm. Given "abc", select the first character in this case "a" permute the remainder, "bc" of the string with the new list, push a into all possible positions pseoducode: function ArrayList permute(String s) { ArrayList permutations if string is null, return null, if string length is equal to zero, add an empty string into the permutations array list a = first character in string remainder = string.substring(1); ArrayList permutedRemainder = permute(remainder); //here's where the n! complexity comes in for every value in permutedRemainder { for(int position = 0; position < string.length; position++) { permutations.add(merge(string, first letter, position); } } return the ArrayList permutations } the only thing left is to write a merge function which will insert the given character into the given position in the string.

Anonymous

Mar 19, 2009

this was my last interview, was tired, and didn't make progress till I ran out of time. Definitely should have ran through a couple practice problems before the interview.