Sherlock and the Valid String

  • + 0 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;

      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";

    }