423 Reconstruct Original Digits from English

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.
  1. 1.
    Input contains only lowercase English letters.
  2. 2.
    Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
  3. 3.
    Input length is less than 50,000.
Example 1:
Input: "owoztneoer"
Output: "012"
Example 2:
Input: "fviefuro"
Output: "45"
The Idea: You can get really creative with this problem. This following approach beats 100% of python3 submissions. This idea goes as follows. First identify groups that can uniquely identify a character in the string. In the first group, we can use z, w, u, x, and g to uniquely identify numbers 0, 2, 4, 6, and 8. The remaining characters are ambiguous, so we create a second group. This group assumes that all the occurrences of the first group are gone. It is only when the first group of numbers are gone that we can uniquely identify the next group of numbers. We find that o, r, f, and s can be used to uniquely identify 1, 3, 5, and 7. Repeat the same idea for the last group. Now run the string through a counter to get a distribution of the string. Through a single iteration of all 3 groups, we should be able to identify all the numbers.
Complexity: O(n + nlogn) time and O(1) space
from collections import Counter
class Solution:
g1 = {'z': ('zero', 0), 'w': ('two', 2), 'u': ('four', 4), 'x': ('six', 6), 'g': ('eight', 8)}
g2 = {'o': ('one', 1), 'r': ('three', 3), 'f': ('five', 5), 's': ('seven', 7)}
g3 = {'i': ('nine', 9)}
iter = [g1, g2, g3]
def originalDigits(self, s):
:type s: str
:rtype: str
c = Counter(s)
sol = []
for d in Solution.iter:
for unique, number in d.items():
if unique in c:
how_many = c[unique]
for _ in range(how_many):
for char in number[0]:
c[char] -= how_many
if c[char] == 0:
del c[char]
return ''.join(str(num) for num in sol)