Facebook Pixel

273. Integer to English Words

Problem Description

This problem asks you to convert a non-negative integer into its English words representation.

Given a non-negative integer num, you need to return a string that represents the number spelled out in English words.

For example:

  • Input: 123 → Output: "One Hundred Twenty Three"
  • Input: 12345 → Output: "Twelve Thousand Three Hundred Forty Five"
  • Input: 1234567 → Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
  • Input: 0 → Output: "Zero"

The solution breaks down the problem by:

  1. Handling special cases: Numbers from 0-19 have unique names ("Zero", "One", "Two", ..., "Nineteen")

  2. Handling tens: Numbers like 20, 30, 40, etc. have their own names ("Twenty", "Thirty", "Forty", ...)

  3. Processing groups of three digits: The algorithm processes the number in groups of three digits from left to right, adding appropriate scale words ("Billion", "Million", "Thousand") after each group.

  4. Using a helper function transfer(): This function converts numbers less than 1000 into words:

    • If the number is less than 20, it uses the lt20 array directly
    • If the number is less than 100, it combines the tens place with the ones place
    • If the number is less than 1000, it processes the hundreds place first, then recursively handles the remainder
  5. Main logic: The algorithm starts with the billions place (1,000,000,000) and works down, extracting each group of three digits, converting them to words using the transfer() function, and appending the appropriate scale word.

The final result strips any trailing spaces and returns the complete English representation of the number.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

When we think about how we naturally read numbers in English, we notice a pattern. We don't read a large number like 1,234,567 digit by digit. Instead, we group digits and apply scale words based on their position.

The key insight is that English number representation follows a hierarchical structure based on groups of three digits. We say "One Million, Two Hundred Thirty Four Thousand, Five Hundred Sixty Seven" - notice how we're essentially breaking the number into chunks of three digits (1, 234, 567) and applying scale words (Million, Thousand) to each chunk.

This leads us to think about the problem in terms of:

  1. Recurring patterns: Numbers within each group of three digits (0-999) follow the same naming pattern regardless of their position in the larger number. Whether it's "234" in the thousands place or "567" in the ones place, the way we say "Two Hundred Thirty Four" or "Five Hundred Sixty Seven" remains the same.

  2. Scale separation: The scales in English (Billion, Million, Thousand) each represent 1000x the previous scale. This means we can process the number by repeatedly dividing by 1000.

  3. Base cases for naming: We observe that:

    • Numbers 0-19 have unique, non-pattern-based names
    • Numbers 20-99 follow a pattern of [tens_name] + [ones_name]
    • Numbers 100-999 follow a pattern of [hundreds_digit] + "Hundred" + [remainder]

This recursive structure naturally suggests a solution where we:

  • Process the number from the largest scale (billions) down to the smallest
  • For each scale, extract the relevant three-digit group
  • Convert that three-digit group to words using the same logic regardless of scale
  • Append the appropriate scale word
  • Move to the next smaller scale

The beauty of this approach is that once we solve how to convert any number less than 1000 to words, we can reuse that logic for every three-digit group in the larger number, just adding the appropriate scale word after each group.

Solution Approach

The implementation uses a divide-and-conquer strategy with careful handling of English number naming conventions.

Data Structures Setup:

First, we define three arrays to store the English words:

  • lt20: Array containing words for numbers 0-19, since these have unique names that don't follow a pattern
  • tens: Array for multiples of 10 (20, 30, 40, ..., 90)
  • thousands: Array containing scale words in descending order: ['Billion', 'Million', 'Thousand', '']

Helper Function - transfer(num):

This recursive function converts any number less than 1000 into its English representation:

  1. Base case: If num == 0, return empty string (to avoid adding extra words for trailing zeros)

  2. Numbers less than 20: Directly look up in lt20 array and add a space: lt20[num] + ' '

  3. Numbers 20-99: Combine the tens place with ones place:

    • Get tens word: tens[num // 10]
    • Recursively process remainder: transfer(num % 10)
    • Return: tens[num // 10] + ' ' + transfer(num % 10)
  4. Numbers 100-999: Process hundreds first, then remainder:

    • Get hundreds digit word: lt20[num // 100]
    • Add "Hundred"
    • Recursively process remainder: transfer(num % 100)
    • Return: lt20[num // 100] + ' Hundred ' + transfer(num % 100)

Main Algorithm:

  1. Special case: If num == 0, immediately return 'Zero'

  2. Initialize variables:

    • i = 1000000000 (1 billion - starting with the largest scale)
    • j = 0 (index for thousands array)
    • res = [] (result array to build the string)
  3. Process each scale group:

    while i > 0:
        if num // i != 0:  # If there's a non-zero group at this scale
            res.append(transfer(num // i))  # Convert the group to words
            res.append(thousands[j])        # Add scale word
            res.append(' ')                  # Add space separator
            num %= i                         # Remove processed digits
        j += 1                              # Move to next scale word
        i //= 1000                          # Move to next smaller scale
  4. Final processing:

    • Join all parts: ''.join(res)
    • Strip trailing spaces: .strip()

Example Walkthrough for 1234567:

  • First iteration (i=1000000000): 1234567 // 1000000000 = 0, skip
  • Second iteration (i=1000000):
    • 1234567 // 1000000 = 1
    • Add: transfer(1) → "One "
    • Add: "Million"
    • Add: " "
    • Update: num = 234567
  • Third iteration (i=1000):
    • 234567 // 1000 = 234
    • Add: transfer(234) → "Two Hundred Thirty Four "
    • Add: "Thousand"
    • Add: " "
    • Update: num = 567
  • Fourth iteration (i=1):
    • 567 // 1 = 567
    • Add: transfer(567) → "Five Hundred Sixty Seven "
    • Add: "" (empty string for ones place)
    • Add: " "

Result after joining and stripping: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Ready to land your dream job?

Unlock your dream job with a 3-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through converting the number 12345 to its English representation.

Initial Setup:

  • Input: 12345
  • We have our arrays ready:
    • lt20 = ['', 'One', 'Two', ..., 'Nineteen']
    • tens = ['', '', 'Twenty', 'Thirty', ..., 'Ninety']
    • thousands = ['Billion', 'Million', 'Thousand', '']

Main Algorithm Process:

Starting with i = 1000000000 (1 billion), j = 0, res = []

Iteration 1 (Billions):

  • Check: 12345 // 1000000000 = 0
  • Since it's 0, skip this scale
  • Update: j = 1, i = 1000000

Iteration 2 (Millions):

  • Check: 12345 // 1000000 = 0
  • Since it's 0, skip this scale
  • Update: j = 2, i = 1000

Iteration 3 (Thousands):

  • Check: 12345 // 1000 = 12
  • Since it's non-zero, process this group:
    • Call transfer(12):
      • 12 is less than 20
      • Return: lt20[12] + ' ' = "Twelve "
    • Add to result: res = ["Twelve "]
    • Add scale word: res = ["Twelve ", "Thousand"]
    • Add space: res = ["Twelve ", "Thousand", " "]
    • Update number: num = 12345 % 1000 = 345
  • Update: j = 3, i = 1

Iteration 4 (Ones/Hundreds):

  • Check: 345 // 1 = 345
  • Since it's non-zero, process this group:
    • Call transfer(345):
      • 345 >= 100, so process hundreds
      • Hundreds digit: 345 // 100 = 3
      • Build: lt20[3] + ' Hundred ' = "Three Hundred "
      • Process remainder: transfer(345 % 100) = transfer(45)
        • 45 >= 20 and < 100
        • Tens: tens[45 // 10] = tens[4] = "Forty"
        • Ones: transfer(45 % 10) = transfer(5)
          • 5 < 20, return lt20[5] + ' ' = "Five "
        • Return: "Forty " + "Five " = "Forty Five "
      • Complete: "Three Hundred " + "Forty Five " = "Three Hundred Forty Five "
    • Add to result: res = ["Twelve ", "Thousand", " ", "Three Hundred Forty Five "]
    • Add scale word: thousands[3] = "" (empty for ones place)
    • Add space: res = ["Twelve ", "Thousand", " ", "Three Hundred Forty Five ", "", " "]
  • Update: i = 0, loop ends

Final Processing:

  • Join result: "Twelve Thousand Three Hundred Forty Five "
  • Strip trailing spaces: "Twelve Thousand Three Hundred Forty Five"

Output: "Twelve Thousand Three Hundred Forty Five"

The algorithm successfully breaks down 12345 into two groups: "12" (thousands) and "345" (ones), converts each group independently using the transfer() function, and combines them with the appropriate scale word "Thousand".

Solution Implementation

1class Solution:
2    def numberToWords(self, num: int) -> str:
3        """
4        Convert an integer to its English words representation.
5      
6        Args:
7            num: Integer between 0 and 2^31 - 1
8          
9        Returns:
10            String representation of the number in English words
11        """
12        # Special case for zero
13        if num == 0:
14            return 'Zero'
15      
16        # Words for numbers less than 20
17        less_than_20 = [
18            '',         # 0
19            'One',      # 1
20            'Two',      # 2
21            'Three',    # 3
22            'Four',     # 4
23            'Five',     # 5
24            'Six',      # 6
25            'Seven',    # 7
26            'Eight',    # 8
27            'Nine',     # 9
28            'Ten',      # 10
29            'Eleven',   # 11
30            'Twelve',   # 12
31            'Thirteen', # 13
32            'Fourteen', # 14
33            'Fifteen',  # 15
34            'Sixteen',  # 16
35            'Seventeen',# 17
36            'Eighteen', # 18
37            'Nineteen', # 19
38        ]
39      
40        # Words for tens places (10, 20, 30, ..., 90)
41        tens_words = [
42            '',         # 0
43            'Ten',      # 10
44            'Twenty',   # 20
45            'Thirty',   # 30
46            'Forty',    # 40
47            'Fifty',    # 50
48            'Sixty',    # 60
49            'Seventy',  # 70
50            'Eighty',   # 80
51            'Ninety',   # 90
52        ]
53      
54        # Scale words for thousands, millions, and billions
55        scale_words = ['Billion', 'Million', 'Thousand', '']
56      
57        def convert_hundreds(num: int) -> str:
58            """
59            Convert a number less than 1000 to words.
60          
61            Args:
62                num: Integer between 0 and 999
63              
64            Returns:
65                String representation with trailing space
66            """
67            if num == 0:
68                return ''
69          
70            # Handle numbers less than 20
71            if num < 20:
72                return less_than_20[num] + ' '
73          
74            # Handle numbers less than 100
75            if num < 100:
76                return tens_words[num // 10] + ' ' + convert_hundreds(num % 10)
77          
78            # Handle numbers from 100 to 999
79            return less_than_20[num // 100] + ' Hundred ' + convert_hundreds(num % 100)
80      
81        # Build result by processing billions, millions, thousands, and ones
82        result = []
83        scale_divisor = 1_000_000_000  # Start with billions
84        scale_index = 0
85      
86        while scale_divisor > 0:
87            # Extract the current group (billions, millions, thousands, or ones)
88            current_group = num // scale_divisor
89          
90            if current_group != 0:
91                # Convert the group to words
92                result.append(convert_hundreds(current_group))
93                # Add the scale word (Billion, Million, Thousand, or empty)
94                result.append(scale_words[scale_index])
95                result.append(' ')
96                # Remove the processed digits
97                num %= scale_divisor
98          
99            # Move to the next scale
100            scale_index += 1
101            scale_divisor //= 1000
102      
103        # Join all parts and remove trailing whitespace
104        return ''.join(result).strip()
105
1class Solution {
2    // Static map to store number-to-word mappings
3    private static Map<Integer, String> numberToWordMap;
4
5    // Static block to initialize the mapping
6    static {
7        numberToWordMap = new HashMap<>();
8      
9        // Single digits (1-9)
10        numberToWordMap.put(1, "One");
11        numberToWordMap.put(2, "Two");
12        numberToWordMap.put(3, "Three");
13        numberToWordMap.put(4, "Four");
14        numberToWordMap.put(5, "Five");
15        numberToWordMap.put(6, "Six");
16        numberToWordMap.put(7, "Seven");
17        numberToWordMap.put(8, "Eight");
18        numberToWordMap.put(9, "Nine");
19      
20        // Special cases (10-19)
21        numberToWordMap.put(10, "Ten");
22        numberToWordMap.put(11, "Eleven");
23        numberToWordMap.put(12, "Twelve");
24        numberToWordMap.put(13, "Thirteen");
25        numberToWordMap.put(14, "Fourteen");
26        numberToWordMap.put(15, "Fifteen");
27        numberToWordMap.put(16, "Sixteen");
28        numberToWordMap.put(17, "Seventeen");
29        numberToWordMap.put(18, "Eighteen");
30        numberToWordMap.put(19, "Nineteen");
31      
32        // Tens (20-90)
33        numberToWordMap.put(20, "Twenty");
34        numberToWordMap.put(30, "Thirty");
35        numberToWordMap.put(40, "Forty");
36        numberToWordMap.put(50, "Fifty");
37        numberToWordMap.put(60, "Sixty");
38        numberToWordMap.put(70, "Seventy");
39        numberToWordMap.put(80, "Eighty");
40        numberToWordMap.put(90, "Ninety");
41      
42        // Scale units
43        numberToWordMap.put(100, "Hundred");
44        numberToWordMap.put(1000, "Thousand");
45        numberToWordMap.put(1000000, "Million");
46        numberToWordMap.put(1000000000, "Billion");
47    }
48
49    /**
50     * Converts an integer to its English words representation
51     * @param num The integer to convert (0 <= num <= 2^31 - 1)
52     * @return The English words representation of the number
53     */
54    public String numberToWords(int num) {
55        // Handle special case of zero
56        if (num == 0) {
57            return "Zero";
58        }
59      
60        StringBuilder result = new StringBuilder();
61      
62        // Process billions, millions, and thousands
63        for (int scale = 1000000000; scale >= 1000; scale /= 1000) {
64            if (num >= scale) {
65                // Convert the group of up to 3 digits and append the scale word
66                result.append(convertThreeDigits(num / scale))
67                      .append(' ')
68                      .append(numberToWordMap.get(scale));
69                num %= scale;
70            }
71        }
72      
73        // Process remaining digits (less than 1000)
74        if (num > 0) {
75            result.append(convertThreeDigits(num));
76        }
77      
78        // Remove the leading space and return
79        return result.substring(1);
80    }
81
82    /**
83     * Converts a number with up to 3 digits to its English words representation
84     * @param num The number to convert (0 < num < 1000)
85     * @return The English words representation with a leading space
86     */
87    private String convertThreeDigits(int num) {
88        StringBuilder result = new StringBuilder();
89      
90        // Process hundreds place
91        if (num >= 100) {
92            result.append(' ')
93                  .append(numberToWordMap.get(num / 100))
94                  .append(' ')
95                  .append(numberToWordMap.get(100));
96            num %= 100;
97        }
98      
99        // Process tens and ones places
100        if (num > 0) {
101            // Numbers 1-19 or multiples of 10 (20, 30, ..., 90)
102            if (num < 20 || num % 10 == 0) {
103                result.append(' ')
104                      .append(numberToWordMap.get(num));
105            } 
106            // Numbers 21-99 (excluding multiples of 10)
107            else {
108                result.append(' ')
109                      .append(numberToWordMap.get(num / 10 * 10))  // Tens place
110                      .append(' ')
111                      .append(numberToWordMap.get(num % 10));       // Ones place
112            }
113        }
114      
115        return result.toString();
116    }
117}
118
1class Solution {
2public:
3    /**
4     * Converts a number to its English words representation
5     * @param num - The number to convert (0 <= num <= 2^31 - 1)
6     * @return The English words representation of the number
7     */
8    string numberToWords(int num) {
9        // Special case for zero
10        if (num == 0) return "Zero";
11      
12        return convertToWords(num);
13    }
14  
15private:
16    /**
17     * Helper function to convert numbers to words recursively
18     * @param x - The number to convert
19     * @return The English words representation
20     */
21    string convertToWords(int x) {
22        // Dictionary for numbers 0-19
23        vector<string> onesAndTeens = {
24            "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
25            "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
26            "Seventeen", "Eighteen", "Nineteen"
27        };
28      
29        // Dictionary for tens (20, 30, 40, ...)
30        vector<string> tens = {
31            "", "", "Twenty", "Thirty", "Forty", "Fifty", 
32            "Sixty", "Seventy", "Eighty", "Ninety"
33        };
34      
35        string result = "";
36      
37        // Handle numbers 0-19
38        if (x <= 19) {
39            result = onesAndTeens[x];
40        }
41        // Handle numbers 20-99
42        else if (x < 100) {
43            int tensDigit = x / 10;
44            int onesDigit = x % 10;
45            result = tens[tensDigit] + " " + convertToWords(onesDigit);
46        }
47        // Handle numbers 100-999
48        else if (x < 1000) {
49            int hundreds = x / 100;
50            int remainder = x % 100;
51            result = onesAndTeens[hundreds] + " Hundred " + convertToWords(remainder);
52        }
53        // Handle numbers 1,000-999,999
54        else if (x < 1000000) {
55            int thousands = x / 1000;
56            int remainder = x % 1000;
57            result = convertToWords(thousands) + " Thousand " + convertToWords(remainder);
58        }
59        // Handle numbers 1,000,000-999,999,999
60        else if (x < 1000000000) {
61            int millions = x / 1000000;
62            int remainder = x % 1000000;
63            result = convertToWords(millions) + " Million " + convertToWords(remainder);
64        }
65        // Handle numbers 1,000,000,000 and above
66        else {
67            int billions = x / 1000000000;
68            int remainder = x % 1000000000;
69            result = convertToWords(billions) + " Billion " + convertToWords(remainder);
70        }
71      
72        // Remove extra spaces and return trimmed result
73        return trimResult(result);
74    }
75  
76    /**
77     * Helper function to trim extra spaces from the result string
78     * @param s - The string to trim
79     * @return The trimmed string
80     */
81    string trimResult(const string& s) {
82        string result;
83        bool lastWasSpace = false;
84      
85        // Remove leading, trailing, and consecutive spaces
86        for (char c : s) {
87            if (c == ' ') {
88                if (!lastWasSpace && !result.empty()) {
89                    result += c;
90                }
91                lastWasSpace = true;
92            } else {
93                result += c;
94                lastWasSpace = false;
95            }
96        }
97      
98        // Remove trailing space if exists
99        if (!result.empty() && result.back() == ' ') {
100            result.pop_back();
101        }
102      
103        return result;
104    }
105};
106
1/**
2 * Converts a number to its English words representation
3 * @param num - The number to convert (0 <= num <= 2^31 - 1)
4 * @returns The English words representation of the number
5 */
6function numberToWords(num: number): string {
7    // Special case for zero
8    if (num === 0) return 'Zero';
9
10    /**
11     * Helper function to convert numbers to words recursively
12     * @param x - The number to convert
13     * @returns The English words representation
14     */
15    const convertToWords = (x: number): string => {
16        // Dictionary for numbers 0-19
17        const onesAndTeens: string[] = [
18            '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
19            'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen',
20            'Seventeen', 'Eighteen', 'Nineteen'
21        ];
22      
23        // Dictionary for tens (20, 30, 40, ...)
24        const tens: string[] = [
25            '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 
26            'Sixty', 'Seventy', 'Eighty', 'Ninety'
27        ];
28      
29        let result: string = '';
30
31        // Handle numbers 0-19
32        if (x <= 19) {
33            result = onesAndTeens[x] ?? '';
34        }
35        // Handle numbers 20-99
36        else if (x < 100) {
37            const tensDigit: number = Math.floor(x / 10);
38            const onesDigit: number = x % 10;
39            result = `${tens[tensDigit]} ${convertToWords(onesDigit)}`;
40        }
41        // Handle numbers 100-999
42        else if (x < 1000) {
43            const hundreds: number = Math.floor(x / 100);
44            const remainder: number = x % 100;
45            result = `${onesAndTeens[hundreds]} Hundred ${convertToWords(remainder)}`;
46        }
47        // Handle numbers 1,000-999,999
48        else if (x < 1000000) {
49            const thousands: number = Math.floor(x / 1000);
50            const remainder: number = x % 1000;
51            result = `${convertToWords(thousands)} Thousand ${convertToWords(remainder)}`;
52        }
53        // Handle numbers 1,000,000-999,999,999
54        else if (x < 1000000000) {
55            const millions: number = Math.floor(x / 1000000);
56            const remainder: number = x % 1000000;
57            result = `${convertToWords(millions)} Million ${convertToWords(remainder)}`;
58        }
59        // Handle numbers 1,000,000,000 and above
60        else {
61            const billions: number = Math.floor(x / 1000000000);
62            const remainder: number = x % 1000000000;
63            result = `${convertToWords(billions)} Billion ${convertToWords(remainder)}`;
64        }
65
66        // Remove extra spaces and return trimmed result
67        return result.trim();
68    };
69
70    return convertToWords(num);
71}
72

Time and Space Complexity

Time Complexity: O(1)

The algorithm processes a fixed maximum of 4 groups (billions, millions, thousands, and ones), regardless of the input size. For each group:

  • The transfer function is called with a number less than 1000
  • Within transfer, there are at most 3 recursive calls (for hundreds, tens, and ones)
  • Each operation (division, modulo, array access) takes constant time

Since the input is bounded by a 32-bit integer (maximum value ~2.1 billion), the number of iterations in the while loop is always exactly 4. The recursion depth in transfer is at most 3 levels. Therefore, the total number of operations is constant.

Space Complexity: O(1)

The space usage includes:

  • Three fixed-size arrays (lt20, tens, thousands) with a total of 34 string elements
  • The res list which stores at most 4 groups × 3 components (number word, scale word, space) = 12 elements
  • The recursion stack for transfer function with maximum depth of 3
  • A few integer variables (i, j, num)

All space requirements are bounded by constants that don't scale with the input value, resulting in constant space complexity.

Common Pitfalls

1. Incorrect Handling of Zero Groups in the Middle

One of the most common pitfalls is not properly handling zero groups within a number. For example, the number 1000050 should be "One Million Fifty", not "One Million Thousand Fifty" or "One Million Zero Thousand Fifty".

Problem Code Example:

# Incorrect approach that might add unnecessary words
if num // scale_divisor >= 0:  # Wrong condition
    result.append(convert_hundreds(num // scale_divisor))
    result.append(scale_words[scale_index])

Solution: Always check if the current group is non-zero before adding its words and scale:

if num // scale_divisor != 0:  # Correct: only process non-zero groups
    result.append(convert_hundreds(num // scale_divisor))
    result.append(scale_words[scale_index])
    result.append(' ')

2. Improper Space Management

Another frequent issue is ending up with multiple consecutive spaces or trailing spaces in the final result due to inconsistent space handling in the helper function.

Problem Scenarios:

  • When convert_hundreds(0) returns an empty string but spaces are still added
  • When recursively calling for numbers ending in zero (like 20, 100, etc.)

Example of problematic output:

  • 120 might become "One Hundred Twenty " (extra spaces)
  • 100 might become "One Hundred " (trailing spaces from empty remainder)

Solution:

  1. Make the helper function consistently return strings with trailing spaces for non-zero values
  2. Always strip the final result to remove any trailing whitespace
  3. Handle the base case of 0 by returning an empty string (no spaces)
def convert_hundreds(num: int) -> str:
    if num == 0:
        return ''  # Return empty string, no spaces
    # ... rest of the logic ensures consistent spacing
  
# In main function:
return ''.join(result).strip()  # Strip removes all trailing spaces

3. Off-by-One Errors in Array Indexing

The tens_words array indexing can be tricky because the index needs to map correctly to the tens digit.

Problem Example:

# Incorrect: This would give wrong tens words
tens_words = ['Twenty', 'Thirty', 'Forty', ...]  # Missing placeholders
return tens_words[num // 10 - 2] + ...  # Complex offset calculation

Solution: Use a properly indexed array with empty strings as placeholders:

tens_words = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
# Now num // 10 directly gives the correct index
return tens_words[num // 10] + ' ' + convert_hundreds(num % 10)

4. Forgetting the Special Case of Zero

The number 0 is a special case that must be handled separately at the beginning of the main function. Without this check, the algorithm would return an empty string.

Problem:

# Without special case handling
def numberToWords(self, num: int) -> str:
    # Directly start processing...
    # When num=0, all divisions result in 0, nothing gets added to result
    return ''.join(result).strip()  # Returns empty string!

Solution:

def numberToWords(self, num: int) -> str:
    if num == 0:
        return 'Zero'  # Handle special case first
    # ... rest of the algorithm

5. Integer Division vs Float Division

Using float division (/) instead of integer division (//) can cause issues when using the result as an array index.

Problem:

current_group = num / scale_divisor  # Returns float
tens_digit = num / 10  # Returns float
less_than_20[num / 100]  # TypeError: list indices must be integers

Solution: Always use integer division (//) when working with array indices:

current_group = num // scale_divisor
tens_digit = num // 10
less_than_20[num // 100]
Discover Your Strengths and Weaknesses: Take Our 3-Minute Quiz to Tailor Your Study Plan:

What does the following code do?

1def f(arr1, arr2):
2  i, j = 0, 0
3  new_arr = []
4  while i < len(arr1) and j < len(arr2):
5      if arr1[i] < arr2[j]:
6          new_arr.append(arr1[i])
7          i += 1
8      else:
9          new_arr.append(arr2[j])
10          j += 1
11  new_arr.extend(arr1[i:])
12  new_arr.extend(arr2[j:])
13  return new_arr
14
1public static List<Integer> f(int[] arr1, int[] arr2) {
2  int i = 0, j = 0;
3  List<Integer> newArr = new ArrayList<>();
4
5  while (i < arr1.length && j < arr2.length) {
6      if (arr1[i] < arr2[j]) {
7          newArr.add(arr1[i]);
8          i++;
9      } else {
10          newArr.add(arr2[j]);
11          j++;
12      }
13  }
14
15  while (i < arr1.length) {
16      newArr.add(arr1[i]);
17      i++;
18  }
19
20  while (j < arr2.length) {
21      newArr.add(arr2[j]);
22      j++;
23  }
24
25  return newArr;
26}
27
1function f(arr1, arr2) {
2  let i = 0, j = 0;
3  let newArr = [];
4  
5  while (i < arr1.length && j < arr2.length) {
6      if (arr1[i] < arr2[j]) {
7          newArr.push(arr1[i]);
8          i++;
9      } else {
10          newArr.push(arr2[j]);
11          j++;
12      }
13  }
14  
15  while (i < arr1.length) {
16      newArr.push(arr1[i]);
17      i++;
18  }
19  
20  while (j < arr2.length) {
21      newArr.push(arr2[j]);
22      j++;
23  }
24  
25  return newArr;
26}
27

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More