#273
Integer to English Words
HardMathStringRecursionHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach builds on the brute force method but optimizes the way we handle the conversion of numbers into words. By using a helper function for numbers less than 1000 and processing the number in chunks, we reduce redundancy and improve efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Create a helper function to convert numbers less than 1000 to words.
- 2Step 2: Use a loop to process the input number in chunks of three digits (thousands).
- 3Step 3: Concatenate the results from the helper function with the appropriate place values.
solution.py25 lines
1# Full working Python code
2class Solution:
3 def numberToWords(self, num: int) -> str:
4 if num == 0:
5 return 'Zero'
6 below_20 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
7 tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
8 thousands = ['', 'Thousand', 'Million', 'Billion']
9
10 def helper(n):
11 if n == 0:
12 return ''
13 elif n < 20:
14 return below_20[n] + ' '
15 elif n < 100:
16 return tens[n // 10] + ' ' + helper(n % 10)
17 else:
18 return below_20[n // 100] + ' Hundred ' + helper(n % 100)
19
20 res = ''
21 for i in range(len(thousands)):
22 if num % 1000 != 0:
23 res = helper(num % 1000) + thousands[i] + ' ' + res
24 num //= 1000
25 return res.strip()ℹ
Complexity note: The time complexity is O(n) because we process each digit of the number only once. The space complexity is O(n) due to the storage of the resulting string.
- 1Breaking down the number into chunks of three digits helps in managing the conversion.
- 2Using a helper function for numbers less than 1000 avoids redundancy.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.