What is an elegant way to find all the permutations of a string. E.g. permutation for ba
, would be ba
and ab
, but what about longer st
This can be done iteratively by simply inserting each letter of the string in turn in all locations of the previous partial results.
We start with [A]
, which with B
becomes [BA, AB]
, and with C
, [CBA, BCA, BAC, CAB, etc]
.
The running time would be O(n!)
, which, for the test case ABCD
, is 1 x 2 x 3 x 4
.
In the above product, the 1
is for A
, the 2
is for B
, etc.
Dart sample:
void main() {
String insertAt(String a, String b, int index)
{
return a.substring(0, index) + b + a.substring(index);
}
List Permute(String word) {
var letters = word.split('');
var p_list = [ letters.first ];
for (var c in letters.sublist(1)) {
var new_list = [ ];
for (var p in p_list)
for (int i = 0; i <= p.length; i++)
new_list.add(insertAt(p, c, i));
p_list = new_list;
}
return p_list;
}
print(Permute("ABCD"));
}