Similar Problems

Similar Problems not available

Check If All Characters Have Equal Number Of Occurrences - Leetcode Solution

Companies:

LeetCode:  Check If All Characters Have Equal Number Of Occurrences Leetcode Solution

Difficulty: Easy

Topics: string hash-table  

Problem Statement:

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).

Input: s = "abacbc" Output: true Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.

Solution:

We can use a hashmap to count the frequency of each character in the given string. Once we have the frequency of each character, we can check if all characters have the same frequency or not.

Let's take an example where the input string is "abacbc". We can traverse the string and count the frequency of each character using a dictionary. Here is how it would look like in Python:

frequency = {}

for i in s:
    if i in frequency:
        frequency[i] += 1
    else:
        frequency[i] = 1

After this loop, the frequency dictionary will contain the frequency of each character in the input string.

Next, we can check if all characters appear the same number of times or not. We can do this by converting the dictionary values to a set and checking if the length of the set is 1. If the length of the set is 1, it means that all characters have the same frequency.

Here is the complete code:

def areOccurrencesEqual(s: str) -> bool:
    frequency = {}

    for i in s:
        if i in frequency:
            frequency[i] += 1
        else:
            frequency[i] = 1

    return len(set(frequency.values())) == 1

The time complexity of this solution is O(n) where n is the length of the input string. The space complexity of this solution is also O(n) because we are creating a dictionary to store the frequency of each character.

Check If All Characters Have Equal Number Of Occurrences Solution Code

1