- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of C++ from the credited upstream file 2999.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 numberOfPowerfulInt(long long start, long long finish, int limit,4 string s) {5 const string a = to_string(start);6 const string b = to_string(finish);7 const string aWithLeadingZeros = string(b.length() - a.length(), '0') + a;8 vector<vector<vector<long>>> mem(9 b.length(), vector<vector<long>>(2, vector<long>(2, -1)));10 const string sWithLeadingZeros = string(b.length() - s.length(), '0') + s;11 return count(aWithLeadingZeros, b, 0, limit, s, true, true, mem);12 }13 14 private:15 16 17 18 long count(const string& a, const string& b, int i, int limit,19 const string& s, bool tight1, bool tight2,20 vector<vector<vector<long>>>& mem) {21 if (i + s.length() == b.length()) {22 const string aMinSuffix = tight123 ? std::string(a.end() - s.length(), a.end())24 : string(s.length(), '0');25 const string bMaxSuffix = tight226 ? std::string(b.end() - s.length(), b.end())27 : string(s.length(), '9');28 const long suffix = stoll(s);29 return stoll(aMinSuffix) <= suffix && suffix <= stoll(bMaxSuffix);30 }31 32 if (mem[i][tight1][tight2] != -1)33 return mem[i][tight1][tight2];34 35 long res = 0;36 const int minDigit = tight1 ? a[i] - '0' : 0;37 const int maxDigit = tight2 ? b[i] - '0' : 9;38 39 for (int d = minDigit; d <= maxDigit; ++d) {40 if (d > limit)41 continue;42 const bool nextTight1 = tight1 && (d == minDigit);43 const bool nextTight2 = tight2 && (d == maxDigit);44 res += count(a, b, i + 1, limit, s, nextTight1, nextTight2, mem);45 }46 47 return mem[i][tight1][tight2] = res;48 }49};50