Taro Logo

Integer to English Words

#241 Most AskedHard
Topics:
ArraysStringsRecursion

Convert a non-negative integer num to its English words representation.

Example 1:

Input: num = 123
Output: "One Hundred Twenty Three"

Example 2:

Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Constraints:

  • 0 <= num <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of the input integer `num` that we need to support (e.g., standard 32-bit signed integer limits)?
  2. How should the number zero (0) be represented in words—should it return "Zero"?
  3. Are there any specific formatting requirements regarding capitalization, spacing (e.g., single spaces between words), or punctuation?
  4. Should I handle negative numbers, or is the input strictly guaranteed to be a non-negative integer?
  5. Are there any specific naming conventions we should follow for large numbers beyond billions (e.g., trillions, quadrillions), or is the scale limited to billions?

Brute Force Solution

Approach

Converting numbers into English words using a brute force strategy involves breaking the number down into every possible combination of smaller pieces and manually looking up the word for each piece. You would exhaustively list and check every conceivable way to translate the parts of the number, piece by piece, until you have covered the entire value.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire number as a single block of digits.
  2. Systematically slice the number into every possible smaller grouping of digits, such as single digits, pairs, and triplets.
  3. For every single slice you create, search through a massive, exhaustive list of all possible number translations to find the matching English word.
  4. If a slice represents a value that requires combining multiple words, like twenty and five, try every combination of words until you find the exact match.
  5. Once you have the translations for all the individual slices, line them all up in order.
  6. Check every single combination of translated pieces to ensure nothing was missed or counted twice.
  7. Finally, stitch all the translated pieces together into one complete sentence to form the final English representation of the number.

Code Implementation

class Solution:
    def numberToWords(self, number_value: int) -> str:
        if number_value == 0:
            return "Zero"

        # We map base words to exhaustively cover all individual translation chunks
        digit_translations = {1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty", 90: "Ninety"}

        scale_translations = {100: "Hundred", 1000: "Thousand", 1000000: "Million", 1000000000: "Billion"}

        string_representation = str(number_value)

        # Slicing the number into groupings helps process thousands and millions correctly
        def generate_chunk_words(current_subnumber):
            if current_subnumber == 0:
                return ""
            elif current_subnumber < 20:
                return digit_translations[current_subnumber]
            elif current_subnumber < 100:
                tens_digit = (current_subnumber // 10) * 10
                remainder_digit = current_subnumber % 10
                if remainder_digit == 0:
                    return digit_translations[tens_digit]
                return digit_translations[tens_digit] + " " + digit_translations[remainder_digit]
            else:
                hundreds_digit = current_subnumber // 100
                remainder_value = current_subnumber % 100
                hundred_word = digit_translations[hundreds_digit] + " Hundred"
                if remainder_value == 0:
                    return hundred_word
                return hundred_word + " " + generate_chunk_words(remainder_value)

        accumulated_words = []
        scales = [1000000000, 1000000, 1000, 1]
        scale_names = ["Billion", "Million", "Thousand", ""]

        # Iterating through scales ensures each magnitude is processed in correct order
        for index_counter in range(len(scales)):
            current_scale = scales[index_counter]
            if number_value >= current_scale:
                chunk_value = number_value // current_scale
                number_value %= current_scale
                translated_chunk = generate_chunk_words(chunk_value)
                accumulated_words.append(translated_chunk)
                if scale_names[index_counter]:
                    accumulated_words.append(scale_names[index_counter])

        final_translation_result = " ".join([word for word in accumulated_words if word])

        # Stitching the translated pieces together forms the final complete sentence
        return final_translation_result

Big(O) Analysis

Time Complexity
O(1) – The input size n represents the value of the integer, but since integers are bounded by a fixed maximum limit of 2 to the 31st power minus 1, the number of digits is at most ten. The brute force strategy exhaustively slices and checks this constant number of digits, meaning the number of slicing operations and word lookups does not grow with a variable input. Because the total number of operations is bounded by a constant maximum regardless of the input value, the execution time is constant, which simplifies to O(1).
Space Complexity
–

Optimal Solution

Approach

The optimal strategy mirrors how humans naturally read and speak large numbers by breaking them down into digestible chunks of thousands. Instead of translating the whole number at once, we chop it up from right to left and label each chunk with its proper scale word like thousand, million, or billion.

Here's how the algorithm would work step-by-step:

  1. Handle the special case where the number is literally zero by just returning the word zero.
  2. Establish standard English vocabulary for numbers under twenty, tens multiples up to ninety, and scale names like thousand, million, and billion.
  3. Break the full number down into groups of three digits, moving from right to left, representing ones, thousands, millions, and billions.
  4. For each three-digit group, convert it into words by first looking at the hundreds digit and saying how many hundreds there are.
  5. Take the remaining two digits of the group and convert them using the standard words for numbers up to ninety-nine.
  6. Attach the appropriate scale name to the end of the group, provided the group is not completely empty.
  7. Combine all the translated chunks together with proper spacing to form the final English phrase.

Code Implementation

class Solution:
    def numberToWords(self, input_number: int) -> str:
        # Zero requires a direct check because it does not follow scale naming rules.
        if input_number == 0:
            return "Zero"

        below_twenty_words = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        tens_multiple_words = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        scale_name_words = ["", "Thousand", "Million", "Billion"]

        def convert_three_digits(triplet_number: int) -> str:
            triplet_phrase = ""
            if triplet_number >= 100:
                triplet_phrase += below_twenty_words[triplet_number // 100] + " Hundred "
                triplet_number %= 100
            if triplet_number >= 20:
                triplet_phrase += tens_multiple_words[triplet_number // 10] + " "
                triplet_number %= 10
            if triplet_number > 0:
                triplet_phrase += below_twenty_words[triplet_number] + " "
            return triplet_phrase.strip()

        accumulated_words = ""
        scale_index = 0

        # Processing groups of three digits from right to left maps directly to how humans read numbers.
        while input_number > 0:
            current_triplet = input_number % 1000
            if current_triplet > 0:
                translated_triplet = convert_three_digits(current_triplet)
                scale_suffix = scale_name_words[scale_index]
                current_chunk = translated_triplet + (" " + scale_suffix if scale_suffix else "")
                accumulated_words = current_chunk + (" " + accumulated_words if accumulated_words else "")
            input_number //= 1000
            scale_index += 1

        # Final cleanup ensures standard spacing regardless of trailing or leading spaces in chunks.
        return accumulated_words.strip()

Big(O) Analysis

Time Complexity
O(log₁₀ n) – The time complexity is driven by the number of digits in the input integer n. Since we process the number by breaking it down from right to left into groups of three digits, the number of chunks we evaluate is proportional to log₁₀(n). Within each chunk, a constant number of operations are performed to inspect the hundreds, tens, and ones places. As n grows larger, the number of operations scales logarithmically with the value of n, simplifying to O(log₁₀ n) or simply O(log n).
Space Complexity
O(1) – The algorithm uses a fixed amount of auxiliary space to store standard English vocabulary arrays for words under twenty, tens multiples, and scale names like thousand and billion. The string builder or temporary lists used to gather translated chunks scale proportionally with the number of three-digit groups, but since a 32-bit integer has a maximum value of roughly two billion, the maximum number of chunks is strictly bounded by a constant four. Consequently, the memory required for intermediate variables and output storage does not grow with the input size N, resulting in a constant auxiliary space complexity.

Edge Cases

Input is exactly zero
How to Handle:
Return the explicit string Zero since the standard chunk processing loop would otherwise produce an empty result.
Maximum 32-bit signed integer boundary values
How to Handle:
Use a 64-bit integer type or standard language handling to prevent overflow when processing billions.
Numbers with internal zeros such as 1000015
How to Handle:
Skip empty thousand chunks cleanly without inserting extra spaces or redundant scale words.
Teens and numbers ending in zero like 10, 11, or 20
How to Handle:
Use specialized lookup arrays for numbers from 10 to 19 and tens multipliers to bypass standard teens logic.
Exact multiples of thousands, millions, and billions
How to Handle:
Append scale words only when the corresponding thousand block value is strictly greater than zero.
Negative numbers
How to Handle:
Assume valid non-negative inputs per the problem constraints or prepend a Negative word if extended.
Single digit numbers from 1 to 9
How to Handle:
Map directly to the base units array without invoking any recursive chunking logic.
Numbers with trailing spaces between concatenated chunks
How to Handle:
Accumulate words into a list and join them with a single space to avoid duplicate whitespace.
0/245 completed