We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Number Has Equal Digit Count and Digit Value

Number: 2377

Difficulty: Easy

Paid? No

Companies: Google, J.P. Morgan


Problem Description

Given a 0-indexed string num of length n, determine if for every index i, the digit i occurs exactly num[i] times in num. Return true if the condition holds; otherwise, return false.


Key Insights

  • Count the occurrences of each digit in the string.
  • Each index i of the string represents the digit we want to validate.
  • Convert the character at index i into an integer which represents the expected count for digit i.
  • Compare the actual count from our data structure with this expected count.

Space and Time Complexity

Time Complexity: O(n^2) in the worst-case scenario due to scanning counts for each index (n is small, n <= 10)
Space Complexity: O(1) since we use a fixed-size data structure for counts (size 10)


Solution

We solve the problem by using a counting data structure (array or hash table) to record the number of occurrences for each digit (0-9) in the string. Then iterate over the string indexes: for each index i, convert the character at that index to an integer which indicates the expected frequency of digit i. If the frequency recorded does not match the expected count, the function returns false; otherwise, the function returns true after the check completes for all indexes.


Code Solutions

# Python solution for Check if Number Has Equal Digit Count and Digit Value

def digitCount(num: str) -> bool:
    # Create a list to store the count for digits 0 through 9
    digit_counts = [0] * 10
    
    # Count the occurrences of each digit in the num string
    for ch in num:
        digit_counts[int(ch)] += 1
    
    # Check the condition for every index i in num
    for i, char in enumerate(num):
        # Convert character at index i to integer for the required count
        required_count = int(char)
        # Compare the expected count (required_count) with the count of digit i
        if digit_counts[i] != required_count:
            return False
    return True

# Example Test
print(digitCount("1210"))  # Expected output: True
print(digitCount("030"))   # Expected output: False
← Back to All Questions