GeeksforGeeks » Interview Questions
Adobe Interview Question for Software Engineer/Developer about Algorithms
(8 posts)-
print permutations of a given string in sorted order
-
dude I think question is wrong. How can it be in sorted order, there will be no permutation then.
-
By using the characters a, b, c, d there can be the following sorted permutations.
abcd
abdc
adbc
adcb
bacd
....
dcba -
Sorry.. The correct sequence would be..
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
...
dcba -
It looks fairly easy if we visualize the string as a circularly doubly connected list.
a->b->c->d
insert d before c
a->b->d->c
recurse for permutate(abcd, d, c);
return from recursion and revert back
a->b->c->d
insert c before b
a->c->b->d
recurse for permutate(abcd, c, d);
inside recursion, insert d before b
a->c->d->b
.....permutate(**str, **end, **start) { print(str); node1 = start; while (node1->prev != end) { //Swapping node2 = node1->prev; node3 = node1->next; remove(str, node1); insert(str, node1, node2); permutate(str, node1, end); //Restoring. remove(str, node1); insert(str, node1, node3); node1=node1->prev; } } remove(list, node); //Removes 'node' from the list insert(list, node1, node2); // Inserts 'node1' before 'node2' int main() { createList(&head, &tail, 'a', 'b', 'c', 'd'); permutate(head, head, tail); }Looks like the remove and insert functions should update tail pointer which i have note handled properly.
-
class Test { public static void main(String[] args) { // sort the given string. String input = sort("labb"); permutation(input, ""); } private static void permutation(String input, String sofar) { if (input.equals("")) { System.out.printf("%s,", sofar); } for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (input.indexOf(c, i + 1) != -1) continue; permutation(input.substring(0, i) + input.substring(i + 1), sofar+c); } } } -
can someone suggest an algorithm to the above mentioned question
thanks -
i think this will work.Not sure
first sort the string and then apply this algo
void permutate(char *str,int len,int j){ if (j==len-1){ cout<<str; return; } permutate(str,len,j+1); for (i=j;i<len-1;++i){ swap(a[j],a[i+1]); permutate(str,len,j+1); swap(a[j],a[i+1]); } }call
char str="ABCD";
permutate(str,4,0);
Reply
You must log in to post.