Amazon Interview Question

print all permutations of a string

Interview Answers

Anonymous

Oct 23, 2012

For question like this, the best way to do is recursive not iterative

Anonymous

Oct 23, 2012

Vector & Find_Substring_Permutation(String & s, int n) { Vector::iterator g; Vector a,b; // base case if (n==s.length()) return; for(int i=0;i

Anonymous

Nov 26, 2012

In Groovy it is as simple as: def s = "ease" def results = s*.toCharArray().permutations().unique().collect { it = it.join() } def expected = ['aees', 'aese', 'asee', 'eaes', 'ease', 'eeas', 'eesa', 'esae', 'esea', 'saee', 'seae', 'seea'] assert results.containsAll(expected) && results.size == expected.size

Anonymous

Oct 19, 2012

Here is the answer for integers. Strings would have an identical algorithm. public ArrayList> findPermutations(ArrayList integers) { ArrayList> result = new ArrayList>(); if (integers == null || integers.size() == 0) { return result; } for (int i = 0; i subArray = new ArrayList(); for (int j = 0; j > subResult = this.findPermutations(subArray); for (ArrayList subPerm : subResult) { subPerm.add(integers.get(i)); result.add(subPerm); } ArrayList selfResult = new ArrayList(); selfResult.add(integers.get(i)); result.add(selfResult); } return result; }