Sherlock and the Valid String

  • + 0 comments

    Simple C++ solution, need to calculate two modes.

    string isValid(string s) {
        int cnt[128] = {};
        
        for (char c : s) {
            cnt[c]++;
        }
        
        int mode = *std::max_element(begin(cnt), end(cnt));
        int mode_cnt = std::count(begin(cnt), end(cnt), mode);
        int mode_1_cnt = mode > 1 ? std::count(begin(cnt), end(cnt), mode-1) : 0;
        
        // 1. only mode plus maybe one additional character (removing that character)
        // 2. one mode plus n * (mode-1) (removing 1 char from mode)
        if (mode*mode_cnt >= s.size() - 1 || mode + (mode-1)*mode_1_cnt == s.size()) {
            return "YES";
        } else {
            return "NO";
        }
    }