Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Integer to English Words

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "273" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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

Explanation

Here's a solution for converting non-negative integers to their English word representations, along with an explanation of the approach and complexity analysis.

  • Divide and Conquer: Break down the number into groups of three digits (hundreds, tens, and ones) starting from the right. Process each group independently.
  • Lookup Tables: Use dictionaries to store the English words for numbers less than 20 and for multiples of 10. This avoids complex conditional logic.
  • Handle Place Values: Append the appropriate place value (Thousand, Million, Billion) after processing each group of three digits.

  • Time Complexity: O(1), as the number of operations is bounded by the maximum possible input value (231 - 1), and the lookup tables provide constant-time access. Space Complexity: O(1), as the space used is determined by the size of the lookup tables, which is constant.

Code

    class Solution:
    def numberToWords(self, num: int) -> str:
        less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
                          "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        thousands = ["", "Thousand", "Million", "Billion"]

        def helper(n):
            if n < 20:
                return less_than_20[n]
            elif n < 100:
                return tens[n // 10] + (" " + less_than_20[n % 10]) if n % 10 != 0 else tens[n//10]
            else:
                return less_than_20[n // 100] + " Hundred " + helper(n % 100)

        if num == 0:
            return "Zero"

        result = []
        for i in range(4):
            if num % 1000 != 0:
                result.append(helper(num % 1000) + " " + thousands[i])
            num //= 1000

        return " ".join(result[::-1]).strip()

More from this blog

C

Chatmagic blog

2894 posts