Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check if All Characters Have Equal Number of Occurrences

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1941" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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

Explanation

Here's the solution to determine if a string is "good" based on character frequency, optimized for efficiency:

  • Frequency Counting: Use a dictionary to efficiently count the occurrences of each character in the string.
  • Frequency Comparison: After counting, check if all the character frequencies are the same. Return True if they are, and False otherwise.

  • Runtime Complexity: O(n), where n is the length of the string.

  • Storage Complexity: O(1). Although a dictionary is used, in the worst case (all characters are unique lowercase English letters), the dictionary's size is bounded by a constant (26).

Code

    def is_good_string(s: str) -> bool:
    """
    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).

    For example:
    is_good_string("abacbc") == True
    is_good_string("aaabb") == False
    """
    char_counts = {}
    for char in s:
        char_counts[char] = char_counts.get(char, 0) + 1

    if not char_counts:
        return True  # Empty string case

    first_frequency = list(char_counts.values())[0]
    for frequency in char_counts.values():
        if frequency != first_frequency:
            return False

    return True

More from this blog

C

Chatmagic blog

2894 posts