Approach
Sorting and greedy selection
For Find the Count of Good Integers, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 46 lines of C++ from the credited upstream file 3272.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long countGoodIntegers(int n, int k) {4 const int halfLength = (n + 1) / 2;5 const int minHalf = pow(10, halfLength - 1);6 const int maxHalf = pow(10, halfLength);7 long ans = 0;8 unordered_set<string> seen;9 10 for (int num = minHalf; num < maxHalf; ++num) {11 const string firstHalf = to_string(num);12 const string secondHalf = {firstHalf.rbegin(), firstHalf.rend()};13 const string palindrome = firstHalf + secondHalf.substr(n % 2);14 if (stol(palindrome) % k != 0)15 continue;16 string sortedDigits = palindrome;17 ranges::sort(sortedDigits);18 if (seen.contains(sortedDigits))19 continue;20 seen.insert(sortedDigits);21 vector<int> digitCount(10);22 for (const char c : palindrome)23 ++digitCount[c - '0'];24 25 const int firstDigitChoices = n - digitCount[0];26 long permutations = firstDigitChoices * factorial(n - 1);27 28 29 for (const int freq : digitCount)30 if (freq > 1)31 permutations /= factorial(freq);32 ans += permutations;33 }34 35 return ans;36 }37 38 private:39 long factorial(int n) {40 long res = 1;41 for (int i = 2; i <= n; ++i)42 res *= i;43 return res;44 }45};46