Problem of The Day: Check if Number Has Equal Digit Count and Digit Value
Problem Statement
Solution [Accepted]
class Solution:
def digitCount(self, num: str) -> bool:
freq = {x: 0 for x in range(10)}
for x in num:
freq[int(x)] += 1
for i in range(len(num)):
if int(num[i]) != freq[i]:
return False
return True
time: O(n) where n is the number of digits in num
space: O(1)
public class Solution {
public bool DigitCount(string num) {
Dictionary<int, int> frequency = new Dictionary<int, int>();
for (int i = 0; i < 10; i++) {
frequency[i] = 0;
}
foreach (var c in num) {
if (int.TryParse(c.ToString(), out int key)) {
frequency[key] = frequency.GetValueOrDefault(key, 0) + 1;
}
}
for (int i = 0; i < num.Length; i++) {
var ch = num[i];
if (int.TryParse(ch.ToString(), out int currDigit)) {
if (currDigit != frequency[i])
return false;
}
}
return true;
}
}
Improve CSharp code
public class Solution
{
public bool DigitCount(string num)
{
// Count frequency of each digit (0-9)
int[] freq = new int[10];
foreach (char c in num)
{
int d = c - '0'; // Convert char to digit
freq[d]++;
}
// Validate: at index i, num[i] should equal frequency of digit i
for (int i = 0; i < num.Length; i++)
{
int expected = num[i] - '0';
if (freq[i] != expected)
return false;
}
return true;
}
}
time: O(n) space: O(1)
Leave a comment