- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 46 lines of C++ from the credited upstream file 3490.cpp.
- The implementation visibly relies on hash lookup.
- 1 loop block detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 int beautifulNumbers(int l, int r) {4 return count(to_string(r), 0, true, true,5 false, 0, 1, {}) -6 count(to_string(l - 1), 0, true, true,7 false, 0, 1, {});8 }9 10 private:11 int count(const string& s, int i, bool tight, bool isLeadingZero,12 bool hasZero, int sum, int prod, unordered_map<string, int>&& mem) {13 if (i == s.length()) {14 if (isLeadingZero)15 return 0;16 return (hasZero || prod % sum == 0) ? 1 : 0;17 }18 const string key = hash(i, tight, isLeadingZero, hasZero, sum, prod);19 if (!isLeadingZero && hasZero && !tight)20 return mem[key] = pow(10, s.length() - i);21 if (const auto it = mem.find(key); it != mem.end())22 return it->second;23 24 int res = 0;25 const int maxDigit = tight ? s[i] - '0' : 9;26 27 for (int d = 0; d <= maxDigit; ++d) {28 const bool nextTight = tight && (d == maxDigit);29 const bool nextIsLeadingZero = isLeadingZero && d == 0;30 const bool nextHasZero = !nextIsLeadingZero && d == 0;31 const int nextProd = nextIsLeadingZero ? 1 : prod * d;32 res += count(s, i + 1, nextTight, nextIsLeadingZero, nextHasZero, sum + d,33 nextProd, std::move(mem));34 }35 36 return mem[key] = res;37 }38 39 string hash(int i, bool tight, bool isLeadingZero, bool hasZero, int sum,40 int prod) {41 return to_string(i) + "_" + (tight ? "1" : "0") + "_" +42 (isLeadingZero ? "1" : "0") + "_" + (hasZero ? "1" : "0") + "_" +43 to_string(sum) + "_" + to_string(prod);44 }45};46