algoadvance

Leetcode 2283. Check if Number Has Equal Digit Count and Digit Value

Problem Statement

You need to write a function to determine if a number has equal digit count and digit value. Specifically, given a string num representing a 0-indexed integer, check if for every digit in the string, the count of its digit matches its value. Formally, return true if for every index i in the range 0 <= i < len(num), the digit num[i] appears exactly i times in num. Otherwise, return false.

Example:

Clarifying Questions

  1. Can the string num contain non-digit characters, like letters or symbols?
    • No, num is guaranteed to only contain digits from ‘0’ to ‘9’.
  2. Is there a constraint on the length of the string num?
    • Yes, the length of num will be between 1 and 100 inclusive.
  3. Should the solution handle leading zeros in the string?
    • Yes, consider leading zeros as part of the string.

Strategy

  1. Count Digit Occurrences: We need to count the occurrences of each digit in the string. This can be done using an integer array of size 10 (for each digit from ‘0’ to ‘9’).
  2. Validate Counts: For each index i, check if the digit at that position matches the number of times i appears in the string.
  3. Edge Cases: Ensure to handle edge cases like a single character string and strings with leading zeros.

Code

public class EqualDigitCountAndDigitValue {
    public boolean digitCount(String num) {
        int[] counts = new int[10];
        
        // Count occurrences of each digit
        for (char c : num.toCharArray()) {
            counts[c - '0']++;
        }
        
        // Validate if counts match the digit values at each index
        for (int i = 0; i < num.length(); i++) {
            int expectedCount = num.charAt(i) - '0';
            if (counts[i] != expectedCount) {
                return false;
            }
        }
        
        return true;
    }

    public static void main(String[] args) {
        EqualDigitCountAndDigitValue solution = new EqualDigitCountAndDigitValue();
        
        // Test cases
        String num1 = "1210";
        System.out.println(solution.digitCount(num1));  // Should return true

        String num2 = "030";
        System.out.println(solution.digitCount(num2));  // Should return false
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI