Skip to content

2283. Check if Number Has Equal Digit Count and Digit Value 👍

  • Time: $O(n)$
  • Space: $O(10) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool digitCount(string num) {
    vector<int> count(10);

    for (const char c : num)
      ++count[c - '0'];

    for (int i = 0; i < num.length(); ++i)
      if (count[i] != num[i] - '0')
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public boolean digitCount(String num) {
    int[] count = new int[10];

    for (final char c : num.toCharArray())
      ++count[c - '0'];

    for (int i = 0; i < num.length(); ++i)
      if (count[i] != num.charAt(i) - '0')
        return false;

    return true;
  }
}
1
2
3
4
5
class Solution:
  def digitCount(self, num: str) -> bool:
    count = collections.Counter(num)
    return all(count[str(i)] == int(digit)
               for i, digit in enumerate(num))