LeetCode 3272: Find the Count of Good Integers
Problem Description
Explanation
To solve this problem, we need to generate all possible permutations of digits for a given number of digits n
and check if each permutation is k-palindromic. We can achieve this by recursively generating all permutations and checking if each one is k-palindromic. We should also keep track of leading zeros to ensure that the resulting integers are valid.
Algorithm:
- Initialize a counter to keep track of the count of good integers.
- Generate all permutations of digits of length
n
. - For each permutation:
- Check if it is a palindrome.
- Check if it is divisible by
k
. - If both conditions are met, increment the counter.
- Return the final count of good integers.
Time Complexity:
The time complexity of this approach is O(n!), where n is the number of digits.
Space Complexity:
The space complexity is O(n) for storing the current permutation.
Solutions
class Solution {
public int countGoodNumbers(int n, int k) {
long count = 0;
long mod = 1000000007;
long oddDigits = (k % 2 == 0) ? k / 2 : (k + 1) / 2;
long evenDigits = k / 2;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
count = count * evenDigits % mod;
} else {
count = count * oddDigits % mod;
}
}
return (int) count;
}
}
Loading editor...