Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

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

Explanation:

We can solve this problem by iterating through the given string num and checking if the count of each digit at index i matches the value of the digit itself. If we find any mismatch, we can return false immediately. If we iterate through the entire string without finding any discrepancies, we return true.

Algorithmic Idea:

  1. Iterate through the string num from index 0 to n-1.
  2. For each digit at index i, check if the count of that digit in the entire string matches the digit itself.
  3. If there is a mismatch, return false.
  4. If we finish the loop without finding any mismatches, return true.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input string num.

Space Complexity:

The space complexity of this solution is O(1) as we are using a constant amount of extra space. :

class Solution {
    public boolean hasEqualDigitCountAndValue(String num) {
        for (int i = 0; i < num.length(); i++) {
            int count = 0;
            for (int j = 0; j < num.length(); j++) {
                if (num.charAt(j) - '0' == i) {
                    count++;
                }
            }
            if (count != num.charAt(i) - '0') {
                return false;
            }
        }
        return true;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.