Given a string s, return true if s is a "good" string, or false otherwise. A string s is good if all characters that appear in s have the same number of occurrences (i.e., the same frequency).

The solution uses a HashMap to count the frequency of each character in the string. After building the frequency map, the frequency of the first character is stored as the expected count. The map is then traversed to verify that every character has the same frequency. If any frequency differs, the string is not considered good.

This approach efficiently checks the frequency distribution in a single pass over the string and a single pass over the unique characters.

Java Solution:

import java.util.HashMap;
import java.util.Map;

public class GoodString {

    public static boolean isGoodString(String input) {

        Map<Character, Integer> frequencyMap = new HashMap<>();

        for (char character : input.toCharArray()) {
            frequencyMap.put(
                    character,

frequencyMap.getOrDefault(character, 0) + 1

            );
        }

        int expectedFrequency = -1;

        for (int frequency : frequencyMap.values()) {
            if (expectedFrequency == -1) {
                expectedFrequency = frequency;
            } else if (frequency != expectedFrequency) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {

        String input = "aabbcc";

        if (isGoodString(input)) {
            System.out.println("Good String");
        } else {
            System.out.println("Not a Good String");
        }
    }
}

Output: Good String

Time Complexity: O(n), where n is the length of the string. The string is traversed once to build the frequency map and the unique characters are traversed once to validate frequencies.

Space Complexity: O(k), where k is the number of distinct characters present in the string.

Key Interview Points: • HashMap is an efficient choice for frequency counting problems. • The algorithm validates frequency consistency without sorting the characters. • An alternative approach is to use a HashSet to store frequencies and verify that the set size is exactly one. • This problem tests understanding of frequency maps and collection-based validation techniques.