Sherlock and the Valid String

  • + 0 comments

    A C++ solution with min/max:

    string isValid(string s) {
        std::map<char, int> uniq;
        for (const char c : s) {
            uniq[c]++;
        }
        auto max = std::max_element(uniq.begin(), uniq.end(), 
            [](std::pair<char, int> el1, std::pair<char, int> el2){
                 return el1.second < el2.second;
                 });
        auto min = std::min_element(uniq.begin(), uniq.end(),
            [](std::pair<char, int> el1, std::pair<char, int> el2){
                 return el1.second < el2.second;
                 });
    
        if (std::all_of(uniq.begin(), uniq.end(), [max](const auto el){ return el.second == max->second; } )) {
            return "YES";
        }
        max->second--;
        if (std::all_of(uniq.begin(), uniq.end(), [min](const auto el){ return el.second == min->second; } )) {
            return "YES";
        }
        max->second++;
        min->second--;
        if (std::all_of(uniq.begin(), uniq.end(), [max](const auto el){ return el.second == max->second || el.second == 0; } )) {
            return "YES";
        }
        return "NO";
    }