Find the Count of Good Integers - Problem

You are given two positive integers n and k.

An integer x is called k-palindromic if:

  • x is a palindrome
  • x is divisible by k

An integer is called good if its digits can be rearranged to form a k-palindromic integer.

For example, for k = 2, 2020 can be rearranged to form the k-palindromic integer 2002, whereas 1010 cannot be rearranged to form a k-palindromic integer.

Return the count of good integers containing n digits.

Note: Any integer must not have leading zeros, neither before nor after rearrangement. For example, 1010 cannot be rearranged to form 101.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 5
Output: 27
💡 Note: For 3-digit numbers, we need palindromes like ABA where A∈{1-9}, B∈{0-9}. Count arrangements that form palindromes divisible by 5.
Example 2 — Single Digit
$ Input: n = 1, k = 4
Output: 2
💡 Note: Single digits divisible by 4: only 4 and 8. So count is 2.
Example 3 — Even Length
$ Input: n = 2, k = 6
Output: 4
💡 Note: 2-digit palindromes divisible by 6: must be divisible by both 2 and 3. Examples: 66 (rearrangement of 66).

Constraints

  • 1 ≤ n ≤ 15
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Find the Count of Good Integers INPUT n-digit numbers (n=3) d1 d2 d3 k-palindromic: d1 = d3 5-palindromic examples: 505 515 525 ... n = 3 k = 5 ALGORITHM STEPS 1 Generate Palindromes Build half, mirror it 2 Filter by k Keep only divisible by 5 3 Get Digit Signatures Sort digits as key 4 Count Permutations n!/duplicates, no lead 0 Combinatorial Formula Signature: "055" --> 505 Perms = 3!/1! = 6 Valid (no lead 0) = 4 Sum all unique signatures FINAL RESULT Good integers count 27 OK - Verified Sample Good Integers: 500 505 550 515 151 ... All can form 5-palindromes via digit rearrangement Key Insight: Instead of checking all n-digit numbers, enumerate only k-palindromic numbers (much fewer). For each unique digit signature, count valid permutations using combinatorics: n! / (product of factorial of digit counts). Subtract permutations with leading zeros to get valid n-digit good integers. TutorialsPoint - Find the Count of Good Integers | Combinatorial Enumeration
Asked in
Google 15 Microsoft 12
12.5K Views
Medium Frequency
~45 min Avg. Time
280 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen