- 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
- 30 lines of Python from the credited upstream file 273.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.
1class Solution:2 def numberToWords(self, num: int) -> str:3 if num == 0:4 return 'Zero'5 6 belowTwenty = ['', 'One', 'Two', 'Three',7 'Four', 'Five', 'Six', 'Seven',8 'Eight', 'Nine', 'Ten', 'Eleven',9 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',10 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']11 tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty',12 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']13 14 def helper(num: int) -> str:15 if num < 20:16 s = belowTwenty[num]17 elif num < 100:18 s = tens[num 10] + ' ' + belowTwenty[num % 10]19 elif num < 1000:20 s = helper(num 100) + ' Hundred ' + helper(num % 100)21 elif num < 1000000:22 s = helper(num 1000) + ' Thousand ' + helper(num % 1000)23 elif num < 1000000000:24 s = helper(num 1000000) + ' Million ' + helper(num % 1000000)25 else:26 s = helper(num 1000000000) + ' Billion ' + helper(num % 1000000000)27 return s.strip()28 29 return helper(num)30