Check if Number Has Equal Digit Count and Digit Value — Easy Problem & Solution

You are given a 0-indexed string num of digits. Return true if, for every index i, the digit i occurs exactly num[i] times in num.

  • Difficulty: Easy
  • Topics: Strings, Hash Table, Counting
  • Asked at: TCS, Zoho, Cognizant
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

You are given a 0-indexed string num of digits.

Return true if, for every index i, the digit i occurs exactly num[i] times in num.

Example 1

Input: num = "1210"
Output: true
Explanation: Digit 0 occurs once, digit 1 twice, digit 2 once and digit 3 never — matching 1, 2, 1, 0.

Example 2

Input: num = "030"
Output: false
Explanation: num[0] says digit 0 appears 0 times, but it appears twice.

Example 3

Input: num = "1"
Output: false
Explanation: num[0] claims digit 0 appears once, and it never does.

Constraints

  • 1 <= num.length <= 10
  • num consists of digits.
  • The digits of num are between 0 and 9.

How to solve Check if Number Has Equal Digit Count and Digit Value

The string is a self-describing claim: position i asserts how many times the digit i occurs. Tally first, then verify each claim.

Approach

  1. Build count[0..9] over the characters of num.
  2. For each index i from 0 to n - 1, compare count[i] with the numeric value of num[i].
  3. Return false on the first mismatch, true otherwise.

Why it works

The claim at index i is exactly 'digit i occurs num[i] times', so a full tally followed by a positional comparison is a direct translation of the definition.

Complexity

  • Time — O(n)
  • Space — O(1)

Pitfalls

  • Comparing count[i] with i instead of with the digit at position i checks the wrong thing.
  • Forgetting to convert the character to its numeric value compares a character code against a count.

Reference solution

Python

def digitCount(num: str) -> bool:
    count = [0] * 10
    for ch in num:
        count[int(ch)] += 1
    return all(count[i] == int(num[i]) for i in range(len(num)))

JavaScript

var digitCount = function(num) {
    var count = [];
    for (var t = 0; t < 10; t++) count.push(0);
    for (var i = 0; i < num.length; i++) count[num.charCodeAt(i) - 48]++;
    for (var j = 0; j < num.length; j++) {
        if (count[j] !== num.charCodeAt(j) - 48) return false;
    }
    return true;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 282 strings problems · the whole catalogue