Check if Number Has Equal Digit Count and Digit Value - Problem

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: If num = "1210", then:

  • Digit 0 should appear num[0] = 1 time (it appears 1 time ✓)
  • Digit 1 should appear num[1] = 2 times (it appears 2 times ✓)
  • Digit 2 should appear num[2] = 1 time (it appears 1 time ✓)
  • Digit 3 should appear num[3] = 0 times (it appears 0 times ✓)

All conditions are satisfied, so return true.

Input & Output

Example 1 — Valid Self-Describing Number
$ Input: num = "1210"
Output: true
💡 Note: Digit 0 appears 1 time (num[0]=1), digit 1 appears 2 times (num[1]=2), digit 2 appears 1 time (num[2]=1), digit 3 appears 0 times (num[3]=0). All conditions satisfied.
Example 2 — Invalid Count
$ Input: num = "030"
Output: false
💡 Note: Digit 0 should appear 0 times (num[0]=0), but it appears 2 times in the string. This violates the condition.
Example 3 — Single Digit
$ Input: num = "0"
Output: false
💡 Note: Digit 0 should appear 0 times (num[0]=0), but it actually appears 1 time in the string. This violates the condition.

Constraints

  • 1 ≤ num.length ≤ 10
  • num consists of digits only

Visualization

Tap to expand
Check if Number Has Equal Digit Count and Digit Value INPUT String: num = "1210" Index: 0 1 2 3 Value: 1 2 1 0 Meaning at each index: i=0: digit 0 appears 1 time i=1: digit 1 appears 2 times i=2: digit 2 appears 1 time i=3: digit 3 appears 0 times n = 4 (length) ALGORITHM STEPS 1 Count Digit Frequency Count occurrences of each digit 0-9 in the string Digit: 0 1 2 3 Count: 1 2 1 0 (in "1210") 2 Iterate Each Index For i from 0 to n-1 3 Verify Condition Check: count[i] == num[i] Digit i appears num[i] times? 4 Return Result true if all match, false otherwise FINAL RESULT Verification for "1210": i num[i] count[i] Match 0 1 1 OK 1 2 2 OK 2 1 1 OK 3 0 0 OK All conditions satisfied! Output: true Number satisfies the condition Key Insight: The string num is self-describing: at each index i, the value num[i] tells you how many times the digit i should appear in the entire string. Use a frequency array to count actual occurrences, then compare. Time: O(n), Space: O(1) since we only need to track digits 0-9. TutorialsPoint - Check if Number Has Equal Digit Count and Digit Value | Optimal Solution
Asked in
Google 15 Amazon 12 Meta 8
23.0K Views
Medium Frequency
~8 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen