Any Mistake in the code?

I have written the following code. It is unable to pass all the test cases. Is there any mistake in the code. Please let me know…

include
include
include
using namespace std;

bool compare(string a, string b){
if(a.size() <= b.size() && b.substr(0, a.size())==a){
return false;
}
else if(b.size() <= a.size() && a.substr(0, b.size())==b){
return true;
}
else{
return a<b;
}
}

int main(){
int n;
cin >> n;
cin.get();
string s[100];

for(int i=0; i<n; i++){
    getline(cin, s[i]);
}

sort(s, s+n, compare);
for(int i=0; i<n; i++){
    cout << s[i] << endl;
}
return 0;

}

According to the constraints given in the question N<=1000 but you have restricted your array size to 100.
For this question you can make an array of strings and then sort it according to the condition that if there is a prefix match between two string, sort in decreasing order of length. Use C++ inbuilt sort function with a custom comparator something like this:

bool mycompare( string a, string b)
{
int l1=a.length();int l2=b.length();int flag=-1;
for(int i=0;i<min(l1,l2);i++){
if(a[i]!=b[i])
flag=0;
}
if(flag==-1) // means there is a prefix match
return l1>l2; // so sort decreasing order of length
else
return a<b; //sorting in normal dictionary order when no prefix match
}

Check this with your code and try to correct it.

Thank you so much… :slight_smile: