Technical Interview

Home
Technical Interview
Interview Process
Introduction Questions
Quantitative Problems
Google & Microsoft
Algorithms
Object Oriented
C/C++ Questions
Java Questions
Data Structures
Fundamental Questions
Puzzles
Resume Tips
Added Recently
Links
Contact Us
Submit Question/Answer

 

Write a function to print all the possible permutations of a string. Now, modify the algorithm to discard duplicates.

 

Solutions:

 

#include <iostream.h>

#include <string.h>

const int MAX_STR = 20;

void CopyStr(char *s2, char *s1, int i)

{

for (int j = 0, k = 0, len = strlen(s2); j < len; j++) {

if (i != j) {

s1[k++] = s2[j];

}

}

s1[k] = '\0';

}

void Permute(char *str1, char *str2)

{

int len = strlen(str1);

if (len == 1) {

//If you do not want to print duplicates, put the result in a

// hash and then print the hash table.

cout << str2 << str1 << "\n";

return;

}

for (int i = 0; i < len; i++) {

char currentChar = str1[i];

char str3[MAX_STR];

CopyStr(str1, str3, i);

int len2 = strlen(str2);

str2[len2] = currentChar;

str2[len2+1] = '\0';

Permute(str3, str2);

str2[len2] = '\0';

}

}

int main ()

{

char someStr[MAX_STR], someOtherStr[MAX_STR];

cout << "Enter a string(less then << MAX_STR << "characters:" ";

cin >> someStr;

someOtherStr[0] = '\0';

cout << "\n\nThe permutations of " << someStr <<" are: \n";

Permute(someStr, someOtherStr);

return 1;

}