The code has not passed 1 of the test cases. Pls find the mistake.
#include<bits/stdc++.h>
using namespace std;
bool compare(string x,string y)
{
return x<y;
}
bool compare1(string x,string y)
{
if(x[0]==y[0])
{
if(y.find(x))
return true;
}
return false;
}
int main() {
int n;
cin>>n;
string a[n];
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n,compare);
sort(a,a+n,compare1);
for(int i=0;i<n;i++)
cout<<a[i]<<endl;
return 0;
}
Code giving wrong output
check for this input
3
batman
bat
bats
your code is giving wrong output because your compare function is not correct
correct compare function should be
bool compare(string a, string b) {
int i = 0;
while (a[i] == b[i]) i++;
if (a[i] == '\0')return false;
else if (b[i] == '\0')return true;
return a[i] < b[i];
}
if you want to ask something about this feel free to ask
i hope this helps
if yes show your response with
and don’t forgot to mark doubt as resolved
return a[i] < b[i];
What does the last statement mean?
first we go through each strings
till a[i]==b[i]
after that we check if string a is completed return false else return true
now we return a[i]<b[i]
this is simple compare function
it will execute only when both string are not similar
means if a[i] is smaller than b[i]
then we true else false
understood… thanks!!