what is the difference between these two loops? I was working on a few competitive programming challenges, everytime I was using the first loop variant I was failing and when i changed it to the second kind of loop it passes all the tests:
Loop variant 1:
for(int j=0; j<str1.length() ; j++) {
char ch = str1[j]
int diff = ch-'a';
arr1[diff]++;
}
Loop variant 2:
for(int i =0; i<str1.length() ;i++) {
arr1[str1[i]-'a']++;
}
I understand that this is a silly question but please be patient, I just want to be clear about why the first one is not working.
Example: Find the minimum number of character deletions required for two given strings to be anagrams
Input: cde abc
Output: 4
Incorrect Code
void minDeletions(string str1, string str2) {
if(str1 == str2){
cout << 0 << endl;
return;
}
int arr1[26] = {0};
int diff,diff1;
for(int i =0; i<str1.length() ;i++) {
char ch = str1[i];
diff = ch-'a';
arr1[diff]++;
}
int arr2[26] = {0};
for(int j=0; j<str2.length() ; j++) {
char ch = str2[j];
diff1 = ch-'a';
arr2[diff]++;
}
int count = 0;
for(int k=0; k<26 ; k++){
if(arr1[k]!=arr2[k]){
count += abs(arr1[k]-arr2[k]);
}
}
cout << count << endl;
}
int main() {
string str1,str2;
cin >> str1;
cin >> str2;
minDeletions(str1,str2);
return 0;
}
Example of test case that fails
Input:
fcrxzwscanmligyxyvym
jxwtrhvujlmrpdoqbisbwhmgpmeoke
Output:
30