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:

  1. Initialize a counter to keep track of the count of good integers.
  2. Generate all permutations of digits of length n.
  3. For each permutation:
    • Check if it is a palindrome.
    • Check if it is divisible by k.
    • If both conditions are met, increment the counter.
  4. 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...