Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Reconstruct Original Digits from English

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "423" 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

Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order. Example 1: Input: s = "owoztneoer" Output: "012" Example 2: Input: s = "fviefuro" Output: "45" Constraints: 1 <= s.length <= 105 s[i] is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]. s is guaranteed to be valid.

Explanation

Here's a breakdown of the approach, complexities, and the Python code:

  • Key Idea: The solution leverages the unique letters present in the English spelling of certain digits. For example, 'z' is unique to 'zero', 'w' is unique to 'two', 'u' is unique to 'four', 'x' is unique to 'six', and 'g' is unique to 'eight'. By counting these unique letters first, we can determine the count of corresponding digits and then decrement the count of letters shared with other digit spellings. This process is repeated for other digits until all counts are determined.
  • Order Matters: Processing digits in the correct order (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) ensures accurate counting by utilizing the unique letters efficiently.
  • Building Result: We iterate through the counts of digits to construct a string representation of the sorted digits.

  • Complexity: O(N) runtime, where N is the length of the input string s. O(1) storage, as the character counts and the digits array use constant space.

Code

    def originalDigits(s: str) -> str:
    """
    Given a string s containing an out-of-order English representation of digits 0-9,
    return the digits in ascending order.
    """

    counts = {}
    for char in s:
        counts[char] = counts.get(char, 0) + 1

    digits = [0] * 10

    # Unique letters for some digits
    digits[0] = counts.get('z', 0)
    digits[2] = counts.get('w', 0)
    digits[4] = counts.get('u', 0)
    digits[6] = counts.get('x', 0)
    digits[8] = counts.get('g', 0)

    # Letters used in other digits after extracting unique ones
    digits[1] = counts.get('o', 0) - digits[0] - digits[2] - digits[4]
    digits[3] = counts.get('h', 0) - digits[8]
    digits[5] = counts.get('f', 0) - digits[4]
    digits[7] = counts.get('v', 0) - digits[5]
    digits[9] = counts.get('i', 0) - digits[5] - digits[6] - digits[8]

    result = ""
    for i in range(10):
        result += str(i) * digits[i]

    return result

More from this blog

C

Chatmagic blog

2894 posts