Formatted question description: https://leetcode.ca/all/1941.html

1941. Check if All Characters Have Equal Number of Occurrences

Level

Easy

Description

Given a string s, return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Example 1:

Input: s = “abacbc”

Output: true

Explanation: The characters that appear in s are ‘a’, ‘b’, and ‘c’. All characters occur 2 times in s.

Example 2:

Input: s = “aaabb”

Output: false

Explanation: The characters that appear in s are ‘a’ and ‘b’. ‘a’ occurs 3 times while ‘b’ occurs 2 times, which is not the same number of times.

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

Solution

Use a hash map to store each character’s number of occurrences in s. The length of s should be divisible by the hash map’s size, and each character’s number of occurrences should be the same. In this case, return true. Otherwise, return false.

  • class Solution {
        public boolean areOccurrencesEqual(String s) {
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            int length = s.length();
            for (int i = 0; i < length; i++) {
                char c = s.charAt(i);
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            int size = map.size();
            if (length % size != 0)
                return false;
            int times = length / size;
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                int count = entry.getValue();
                if (count != times)
                    return false;
            }
            return true;
        }
    }
    
  • // OJ: https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
    // Time: O(N)
    // Space: O(C) where C is the range of the characters
    class Solution {
    public:
        bool areOccurrencesEqual(string s) {
            int cnt[26] = {}, mx = 0;
            for (char c : s) {
                mx = max(mx, ++cnt[c - 'a']);
            }
            for (int i = 0; i < 26; ++i) {
                if (cnt[i] && cnt[i] != mx) return false;
            }
            return true;
        }
    };
    
  • # 1941. Check if All Characters Have Equal Number of Occurrences
    # https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
    
    class Solution:
        def areOccurrencesEqual(self, s: str) -> bool:
            counter = collections.Counter(s)
            values = list(counter.values())
            
            for v in values:
                if v != values[0]: return False
            
            return True
    
    

All Problems

All Solutions