Sherlock and the Valid String

  • + 0 comments

    Java 15 solution that passes all test cases:

    public static String isValid(String s) {
        HashMap<Character, Integer> charFreqs = new HashMap<Character, Integer>();
        
        for (int i = 0; i < s.length(); i++) { //Get the frequencies of each character
            char a = s.charAt(i);
            if (charFreqs.containsKey(a)) charFreqs.replace(a, charFreqs.get(a) + 1);
            else charFreqs.put(a,1);
        }
        List<Integer> freqList = new ArrayList<Integer>();
        boolean safeToRemove = true; //Flag for if we've already removed a single character
        
        for (char key : charFreqs.keySet()) { //Create a list of all character frequencies, then sort it
            freqList.add(charFreqs.get(key));
        }
        Collections.sort(freqList);
        int minFreq = freqList.get(0); //The minimum frequency that isn't 1 is our target value, since we can only remove characters from the string.
        if (minFreq == 1) { //If there's a single instance of a given character...
            safeToRemove = false;
            if (freqList.size() > 1) minFreq = freqList.get(1); //...use the second frequency if the list of frequencies has more than one element.
        }
        
        for (int j = 1; j < freqList.size(); j++) {
            int freq = freqList.get(j);
            System.out.println(freq);
            if (freq == 1 && !safeToRemove) return "NO"; //There are multiple characters for which only one instance occurs.
            else if (freq - minFreq == 1) { //If we've already removed a character, we can't remove another. So check if we didn't already do so and then set that flag to false if such is the case.
                if (safeToRemove) safeToRemove = false;
                else return "NO";
            } else if (freq - minFreq > 1) return "NO"; //If a frequency exists that's greater than 1 + the minimum frequency, the string isn't valid.
        }
        
        return "YES";
    }