- 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
- 70 lines of Python from the credited upstream file count-the-number-of-powerful-integers.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks 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.
123 45class Solution(object):6 def numberOfPowerfulInt(self, start, finish, limit, s):7 """8 :type start: int9 :type finish: int10 :type limit: int11 :type s: str12 :rtype: int13 """14 def count(x):15 def length(x):16 result = 017 while x:18 x = 1019 result += 120 return result21 22 result = 023 n = length(x)24 base = 10**n25 l = n-len(s)26 cnt = (limit+1)**l27 for i in xrange(l):28 base = 1029 curr = xbase%1030 cnt = limit+131 result += (min(curr-1, limit)-0+1)*cnt32 if curr > limit:33 break34 else:35 if x%base >= int(s):36 result += 137 return result38 39 return count(finish)-count(start-1)40 41 42434445class Solution2(object):46 def numberOfPowerfulInt(self, start, finish, limit, s):47 """48 :type start: int49 :type finish: int50 :type limit: int51 :type s: str52 :rtype: int53 """54 def count(x):55 result = 056 str_x = str(x)57 l = len(str_x)-len(s)58 cnt = (limit+1)**l59 for i in xrange(l):60 cnt = limit+161 result += (min(int(str_x[i])-1, limit)-0+1)*cnt62 if int(str_x[i]) > limit:63 break64 else:65 if int(str_x[-len(s):]) >= int(s):66 result += 167 return result68 69 return count(finish)-count(start-1)70