We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Sherlock and the Valid String
Sherlock and the Valid String
Sort by
recency
|
2057 Discussions
|
Please Login in order to post a comment
// my code is not passing only one test case can anyone help why ?
string isValid(string s) {
// cnt[i] stores frequency of character i+'a' int cnt[26] = {0}, n = s.length();
for (int i = 0; i < n; i++) { // increasing frequency cnt[s[i] - 'a']++; }
for (int i = 0; i < 26; i++) { // if character i+'a' is not present in string continue if (cnt[i] == 0) continue;
}
return "NO";
}
My C++ solution:
include
include
include
include
include
include
using namespace std;
int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string str;cin>>str; vectorcnt(26,0);unordered_mapmp; for(char &c : str) cnt[c - 'a']++; for(int i=0;i<26;++i){ if(cnt[i]>0){ mp[cnt[i]]++; } } if(mp.size()==1) { cout << "YES\n"; } else if(mp.size()==2){ int fre1,fre2,b1,b2; auto it = mp.begin(); fre1 = it->first;b1 = it->second; it++; fre2 = it->first;b2 = it->second; if((fre1==1&&b1==1)||(fre2==1&&b2==1)|| (abs(fre1-fre2)==1&&(b1==1||b2==1))){ cout << "YES\n"; } else cout << "NO\n"; } else cout << "NO\n"; return 0; }
Test case 14 consists of the letters 'a' through 'y', each appearing 4000 times, in random order. It is expecting a "YES" return, even though by the definitions set forth this is an invalid string.
Either something went wrong in the storage backend for the test cases and a letter got chopped off somehow, or this problem is expecting an incorrect answer.
A correct answer can simply use a character frequency count and some conditionals.
I thought this one would be super easy but got humbled after I couldn't solve it in 15 minutes. Here is my Python solution!