Sherlock and the Valid String

  • + 0 comments

    My C++ solution:

    string isValid(string s) {
        map<char,int> charmap;
        for (char c : s) {
            charmap[c]++;
        }
        
        map<int, int> freqCounts;
        for (auto const& pair : charmap) {
            freqCounts[pair.second]++;
        }
    
        if (freqCounts.size() == 1) {
            return "YES";
        }
    
        if (freqCounts.size() == 2) {
            vector<pair<int, int>> freqs(freqCounts.begin(), freqCounts.end());
            int freq1 = freqs[0].first;
            int count1 = freqs[0].second;
            int freq2 = freqs[1].first;
            int count2 = freqs[1].second;
    
            if ((freq1 == 1 && count1 == 1) || (freq2 == 1 && count2 == 1)) {
                return "YES";
            }
    
            if ((abs(freq1 - freq2) == 1) && (count1 == 1 || count2 == 1)) {
                return "YES";
            }
        }
    
        return "NO";
    }