Problem Description
Given a string s containing an out-of-order English representation of digits 0-9, reconstruct the digits and return them in ascending order.
Key Insights
- Each digit from 0 to 9 when spelled out contains a unique set of letters.
- Some digits contain a letter that doesn't appear in any other digit's spelling; for example, 'z' only appears in "zero".
- By counting the occurrence of each letter in s, we can determine the frequency of some digits directly.
- The digits that don't have a unique letter must be identified after accounting for overlaps with more unique digits.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(1) since the extra space is used for the fixed size frequency table and result digits.
Solution
We use a frequency table to count each character in the input string. Then, we determine the count of each digit using unique characters in the spelling:
- Digit 0: Use the letter 'z' from "zero".
- Digit 2: Use the letter 'w' from "two".
- Digit 4: Use the letter 'u' from "four".
- Digit 6: Use the letter 'x' from "six".
- Digit 8: Use the letter 'g' from "eight".
Once these are determined, we can remove their effects from overlapping letters and deduce:
- Digit 3: Using the letter 'h' from "three" (after removing eight).
- Digit 5: Using the letter 'f' from "five" (after removing four).
- Digit 7: Using the letter 's' from "seven" (after removing six).
- Digit 1: Using the letter 'o' from "one" (after removing zero, two, and four).
- Digit 9: Using the letter 'i' from "nine" (after removing five, six, and eight).
Finally, we form the result string by appending each digit according to its count in ascending order.