Please read the new rule regarding the restriction on the use of AI tools. ×

ThreeKnives's blog

By ThreeKnives, history, 2 hours ago, In English

I was solving the problem1800E2

I came across strange behaviour while comparing strings in c++. My first submission failed on testcase 2, I changed the code to compare string and instead of using "==" wrote my comparator myself and it passed. I fail to understand my mistake in the first implementation.

submission 1: Link

submission 2: Link

Basically my code included

string ta = a.substr(i, min(k, n) - i);
string tb = b.substr(i, min(k, n) - i);
 
if(ta == tb) cout << "YES\n";
else cout << "NO\n";

which failed the testcases then i changed this part of code to

for(int j = i; j < min(n, k); j++) {
    if(a[j] != b[j]) valid = 0;
}

This passed the testcase. I dont understand what was the problem in the first implementation, can anyone point something out that I am too dumb to understand.

Sorry for my poor english, Thanks in advance.

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
2 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by ThreeKnives (previous revision, new revision, compare).

»
2 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Most likely you pass negative length to substr

  • »
    »
    103 minutes ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    The substring code is inside if block with condition if(i < n), could you provide an example where the substring will be getting a negative length.

»
4 minutes ago, # |
  Vote: I like it 0 Vote: I do not like it

In first solve you have continue and in second you have just valid = 0.
So first solve doesn't include the case when valid = 0 comes from the first loop

if (ta != tb) valid = 0;

instead of

if(ta == tb) cout << "YES\n";
else cout << "NO\n";
continue;

would fix that