Reconstruct Original Digits From English Problem
Description
LeetCode Problem 423.
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 <= 10^5
- 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.
Solution
Approach: Count Letters, Then Solve Digits in a Fixed Order
The letters are shuffled, so only their counts matter. The key observation is that some letters appear in exactly one digit word:
| Letter | Only in |
|---|---|
z |
zero |
w |
two |
u |
four |
x |
six |
g |
eight |
So the counts of 0, 2, 4, 6 and 8 can be read directly. Each remaining digit has a letter that is shared only with digits we already know, so subtract those:
his in three and eight:three = h - eightfis in five and four:five = f - foursis in seven and six:seven = s - sixois in one, zero, two and four:one = o - zero - two - fouriis in nine, five, six and eight:nine = i - five - six - eight
The order matters: five must be known before nine, because nine's formula uses it. Finally write each digit d as many times as it was counted, from 0 to 9, which gives the digits in ascending order without sorting.
The input is guaranteed to be valid, so every count comes out non-negative.
Complexity: O(n) time, where n is the length of s: one pass to count letters, then building the answer of at most n / 3 digits. O(1) extra space besides the answer.
import collections
class Solution:
def originalDigits(self, s: str) -> str:
letters = collections.Counter(s)
digit = [0] * 10 # digit[d] = how many times d appears
# Letters found in only one digit word: z(ero), w(two), u(four), x(six), g(eight).
digit[0] = letters["z"]
digit[2] = letters["w"]
digit[4] = letters["u"]
digit[6] = letters["x"]
digit[8] = letters["g"]
# Letters shared only with digits already counted.
digit[3] = letters["h"] - digit[8] # three, eight
digit[5] = letters["f"] - digit[4] # five, four
digit[7] = letters["s"] - digit[6] # seven, six
digit[1] = letters["o"] - digit[0] - digit[2] - digit[4] # one, zero, two, four
digit[9] = letters["i"] - digit[5] - digit[6] - digit[8] # nine, five, six, eight
return "".join(str(d) * digit[d] for d in range(10))