Reconstruct Original Digits from English — LeetCode 423 Python Solution

MediumHash TableMathString
Problem
#423
Reading time
3 min

The problem

Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.

Example

Input
s = "owoztneoer"
Output
"012"

Python solution

Python
class Solution:
    def originalDigits(self, s: str) -> str:
        counter = Counter(s)
        cnt = [0] * 10

        cnt[0] = counter['z']
        cnt[2] = counter['w']
        cnt[4] = counter['u']
        cnt[6] = counter['x']
        cnt[8] = counter['g']

        cnt[3] = counter['h'] - cnt[8]
        cnt[5] = counter['f'] - cnt[4]
        cnt[7] = counter['s'] - cnt[6]

        cnt[1] = counter['o'] - cnt[0] - cnt[2] - cnt[4]
        cnt[9] = counter['i'] - cnt[5] - cnt[6] - cnt[8]

        return ''.join(cnt[i] * str(i) for i in range(10))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 423. Reconstruct Original Digits from English is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 423. Reconstruct Original Digits from English?
LeetCode 423. Reconstruct Original Digits from English is rated Medium on LeetCode.
What is the time complexity of LeetCode 423. Reconstruct Original Digits from English?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 423. Reconstruct Original Digits from English?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 423. Reconstruct Original Digits from English cover?
LeetCode 423. Reconstruct Original Digits from English is tagged Hash Table, Math and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview