LeetCode 1941: Check if All Characters Have Equal Number of Occurrences Solution

Master LeetCode problem 1941 (Check if All Characters Have Equal Number of Occurrences), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1941. Check if All Characters Have Equal Number of Occurrences

Problem Explanation

Explanation:

To solve this problem, we can use a hashmap to count the frequency of each character in the given string. Then, we iterate over the hashmap to check if all characters have the same frequency. If all characters have the same frequency, we return true; otherwise, we return false.

  • Create a hashmap to count the frequency of characters in the string.
  • Iterate over the string and populate the hashmap.
  • Iterate over the hashmap values and check if all values are the same.
  • If all values are the same, return true; otherwise, return false.

Time Complexity: O(n), where n is the length of the input string s.

Space Complexity: O(1) since the hashmap would contain at most 26 entries (lowercase English letters).

Solution Code

class Solution {
    public boolean areOccurrencesEqual(String s) {
        Map<Character, Integer> charFreq = new HashMap<>();
        for(char c : s.toCharArray()) {
            charFreq.put(c, charFreq.getOrDefault(c, 0) + 1);
        }
        
        int freq = -1;
        for(int count : charFreq.values()) {
            if(freq == -1) {
                freq = count;
            } else {
                if(freq != count) {
                    return false;
                }
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1941 (Check if All Characters Have Equal Number of Occurrences)?

This page provides optimized solutions for LeetCode problem 1941 (Check if All Characters Have Equal Number of Occurrences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1941 (Check if All Characters Have Equal Number of Occurrences)?

The time complexity for LeetCode 1941 (Check if All Characters Have Equal Number of Occurrences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1941 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1941 in Java, C++, or Python.

Back to LeetCode Solutions