Sherlock and the Valid String

  • + 0 comments

    Less Spoiler: Possible scenarios: case1: aaabbbcccddd case2.abbbcccddd case3:aaaabbbcccdddd

    Spoiler: // case 1: uniqueFreqs == 1 means: All characters have the same frequency // example: "aabbccdd" all appear twice. The only distinct frequency is 2. // case 2: There are 2 distinct values and one of them is "1" and it occurs only once // example: aaaabbbbc the occurance of 4 (a and b) is 2 and the occurance of 1 is(c) is one. Remove the only letter which appears once // case 3: Frequencies differ by 1, and the higher frequency appears only once example: aaaabbbbccccc

    Java with array Hashmap is also an option I guess.

    public static String isValid(String s) {
        // Step 1: Count character frequencies
        int[] freq = new int[26];
        for (char c : s.toCharArray()) {
            freq[c - 'a']++;
        }
    
        // Step 2: Find the maximum frequency
        int maxFreq = 0;
        for (int f : freq) {
            if (f > maxFreq) {
                maxFreq = f;
            }
        }
    
        // Step 3: Count occurrences of each frequency
        int[] freqCounts = new int[maxFreq + 1];
        for (int f : freq) {
            if (f > 0) {
                freqCounts[f]++;
            }
        }
    
        // Step 4: Analyze frequency counts
        int uniqueFreqs = 0; // Count of unique(non zero) frequencies
        boolean canRemoveOne = false; // Whether we can remove one character to make it valid
    
        for (int i = 1; i < freqCounts.length; i++) {
            if (freqCounts[i] > 0) {
                uniqueFreqs++;
                // Check if we can remove one character to balance frequencies
                if (i < freqCounts.length - 1 && freqCounts[i + 1] == 1) {
                    canRemoveOne = true;
                }
            }
        }
    // case 1: uniqueFreqs == 1 means: All characters have the same frequency
        // example: "aabbccdd" all appear twice. The only distinct frequency is 2.
        // case 2: There are 2 distinct values and one of them is "1" and it occurs only once
        // example: aaaabbbbc  the occurance of 4 (a and b) is 2 and the occurance of 1 is(c) is one. Remove the only letter which appears once
        // case 3: Frequencies differ by 1, and the higher frequency appears only once example: aaaabbbbccccc
        
    		// Step 5: Return the result based on the cases
        if (uniqueFreqs == 1 || (uniqueFreqs == 2 && (freqCounts[1] == 1 || canRemoveOne))) {
            return "YES";
        }
    
        return "NO";
    }