#3272
Find the Count of Good Integers
HardHash TableMathCombinatoricsEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking each number, we can directly calculate how many digit combinations can form a k-palindromic integer based on their frequency. This avoids unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Generate all possible digit frequencies for n digits ensuring the first digit is non-zero.
- 2Step 2: For each frequency, check if it can form a palindrome (at most one digit can have an odd frequency).
- 3Step 3: Count how many of these frequencies are divisible by k.
solution.py17 lines
1from itertools import product
2
3def countGoodIntegers(n, k):
4 count = 0
5 for digits in product(range(10), repeat=n):
6 if digits[0] == 0:
7 continue
8 freq = [0] * 10
9 for d in digits:
10 freq[d] += 1
11 if canFormPalindrome(freq) and sum(d * f for d, f in enumerate(freq)) % k == 0:
12 count += 1
13 return count
14
15def canFormPalindrome(freq):
16 odd_count = sum(1 for f in freq if f % 2 != 0)
17 return odd_count <= 1ℹ
Complexity note: The time complexity is O(n) because we efficiently calculate the digit frequencies and check conditions without generating all numbers explicitly.
- 1A number can only be rearranged into a palindrome if at most one digit has an odd frequency.
- 2Divisibility by k must be checked after confirming the number can form a palindrome.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.