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 <= 10num consists of digits.Use an array to count the frequency of each digit (0-9) in the string. Check if each digit i matches the count specified at num[i].
This C solution uses an array to track the frequency of each digit. It iterates over the input string to populate this frequency array and then checks each digit against the expected count.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as the array size is constant (10 elements).
Instead of storing results in an array, count digits as needed directly against the requirement in the input string.
This approach counts occurrences of each expected digit in-place by iterating over the string multiple times for each digit check.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Count Digits with a Frequency Array | Time Complexity: O(n), where n is the length of the string. |
| Count and Verify In-place | Time Complexity: O(n^2). |
Letter Combinations of a Phone Number - Leetcode 17 • Greg Hogg • 61,943 views views
Watch 9 more video solutions →Practice Check if Number Has Equal Digit Count and Digit Value with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor