Leetcode 2283. Check if Number Has Equal Digit Count and Digit Value
You need to write a function to determine if a number has equal digit count and digit value. Specifically, given a string num
representing a 0-indexed integer, check if for every digit in the string, the count of its digit matches its value. Formally, return true
if for every index i
in the range 0 <= i < len(num)
, the digit num[i]
appears exactly i
times in num
. Otherwise, return false
.
Example:
num = "1210"
Output: true
num = "030"
false
num
contain non-digit characters, like letters or symbols?
num
is guaranteed to only contain digits from ‘0’ to ‘9’.num
?
num
will be between 1 and 100 inclusive.i
, check if the digit at that position matches the number of times i
appears in the string.public class EqualDigitCountAndDigitValue {
public boolean digitCount(String num) {
int[] counts = new int[10];
// Count occurrences of each digit
for (char c : num.toCharArray()) {
counts[c - '0']++;
}
// Validate if counts match the digit values at each index
for (int i = 0; i < num.length(); i++) {
int expectedCount = num.charAt(i) - '0';
if (counts[i] != expectedCount) {
return false;
}
}
return true;
}
public static void main(String[] args) {
EqualDigitCountAndDigitValue solution = new EqualDigitCountAndDigitValue();
// Test cases
String num1 = "1210";
System.out.println(solution.digitCount(num1)); // Should return true
String num2 = "030";
System.out.println(solution.digitCount(num2)); // Should return false
}
}
O(n)
, where n
is the length of the num
string. This is because we have to go through the string to count occurrences and then validate each character’s count.O(1)
, since the size of our auxiliary storage (counts
array) is fixed at 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?