Backtracking runerror

question https://hack.codingblocks.com/contests/c/512/737
showing run error in 3 test case other 6 cases passed
#include
#include
#include
using namespace std;
bool compare(string a,string b){
return a<b;
}
int k=0;
void permutation(string inp,int i,string s[]){
if(i == inp.size()){
s[k]=inp;
k++;
return;
}
for(int j=i;j<inp.size();j++){
swap(inp[i],inp[j]);
permutation(inp,i+1,s);
swap(inp[j],inp[j]);
}
}

int main(){
string inp;
cin>>inp;
string s[100];
permutation(inp,0,s);
int ans =::k;
sort(s,s+ans,compare);
for (int i=0;i<ans;i++){
if(s[i]==s[i+1]){
cout<<s[i];
i++;
}
else{
cout<<s[i];
}
cout<<endl;
}

return 0;
}

Hey Sarthak, run error is because you have taken the array for storing output i.e string s[100]; of max size 100 only but there can be more than 100 permutations of a string with 8 characters. So instead of using array use vectors then there will be no need to give a fixed size at the time of declaration and it will grow automatically according to the output.

1 Like