Leetcode 2283. Check if Number Has Equal Digit Count and Digit Value
The problem is as follows:
You are given a string num
consisting of digits. Return true
if for every digit d
in the string num
, the digit d
appears d
times in the string. Otherwise, return false
.
For example, given the string "1210"
, the number 1
in the 0
th index of the string appears 1
time(s) in the string, the number 2
in the 1
st index appears 2
time(s) in the string, the number 1
in the 2
nd index appears 1
time(s) in the string, and the number 0
in the 3
rd index appears 0
time(s) in the string. Since the counts align with the values, the output should be true
for "1210"
.
d
at position i
appears exactly d
times in the string.true
. Otherwise, return false
.#include <iostream>
#include <vector>
#include <string>
bool digitCount(std::string num) {
std::vector<int> count(10, 0); // Array to count occurrences of each digit
// Count occurrences of each digit
for (char c : num) {
count[c - '0']++;
}
// Check if the digit count matches the expected value
for (int i = 0; i < num.size(); i++) {
int digit = num[i] - '0';
if (count[i] != digit) {
return false;
}
}
return true;
}
int main() {
std::string num = "1210";
std::cout << std::boolalpha << digitCount(num) << std::endl; // Output: true
num = "030";
std::cout << std::boolalpha << digitCount(num) << std::endl; // Output: false
return 0;
}
count
array.Thus, the total time complexity is O(n).
The space complexity is O(1) as we are using a fixed-size array (of size 10) regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?