Description
You are given a 0-indexed string num of length n consisting of digits.
Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.
Example 1:
Input: num = "1210" Output: true Explanation: num[0] = '1'. The digit 0 occurs once in num. num[1] = '2'. The digit 1 occurs twice in num. num[2] = '1'. The digit 2 occurs once in num. num[3] = '0'. The digit 3 occurs zero times in num. The condition holds true for every index in "1210", so return true.
Example 2:
Input: num = "030" Output: false Explanation: num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num. num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num. num[2] = '0'. The digit 2 occurs zero times in num. The indices 0 and 1 both violate the condition, so return false.
Constraints:
n == num.length1 <= n <= 10numconsists of digits.
Solutions
Solution 1: Counting + Enumeration
We can use an array cnt of length 10 to count the occurrences of each digit in the string num. Then, we enumerate each digit in the string num and check if its occurrence count equals the digit itself. If this condition is satisfied for all digits, we return true; otherwise, we return false.
The time complexity is O(n), and the space complexity is O(|Σ|). Here, n is the length of the string num, and |Σ| is the range of possible digit values, which is 10.
PythonJavaC++GoTypeScriptRustC
class Solution: def digitCount(self, num: str) -> bool: cnt = Counter(int(x) for x in num) return all(cnt[i] == int(x) for i, x in enumerate(num))(code-box)
