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.
// 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;
cnt[i]--;
// if we insert all positive frequencies into a set, it should contain
// only 1 element if string is now valid
set<int> myset;
// insert remaining positive frequencies into set
for (int j = 0; j < 26; j++) {
if (cnt[j]) myset.insert(cnt[j]);
}
// if set size is 1, string is now valid
if (myset.size() <= 1) return "YES";
// increase the frequency back again
cnt[i]++;
}
return "NO";
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and the Valid String
You are viewing a single comment's thread. Return to all comments →
// 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";
}