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: true
💡 Note: Digit 0 should appear 0 times (num[0]=0), and it appears 0 times (not counting itself in this context). Wait, this is tricky - digit 0 actually appears 1 time, so this should be false.

Constraints

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

Visualization

Tap to expand
Self-Describing Number Check: "1210"Input String:1210pos 0pos 1pos 2pos 3Verification Rules:Digit 0 should appear 1 timeDigit 1 should appear 2 timesDigit 2 should appear 1 timeDigit 3 should appear 0 timesCount of 0: 1 ✓Count of 1: 2 ✓Count of 2: 1 ✓Count of 3: 0 ✓All conditions satisfied → true
Understanding the Visualization
1
Input
String "1210" where each position represents a digit count requirement
2
Process
Count actual digit frequencies and compare with position requirements
3
Output
Return true if all positions match their count requirements
Key Takeaway
🎯 Key Insight: A self-describing number has the property that digit at position i equals the count of digit i in the entire string
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