Problem 423 · LeetCode 423(opens in a new tab)
Reconstruct Original Digits from English
MediumHash tables
Someone wrote some digits as English words (zero, one, ..., nine), joined the words together, and then mixed up all the letters. You get the result, s.
Return the digits that were written, as a string in ascending order. The input is always a valid mix of some digit words.
Example 1
Input: s = "iehenirteoegnnthe" Output: "1389" Why: the letters spell one, three, eight and nine
2 more examples and the constraints
Example 2
Input: s = "owxsti" Output: "26" Why: the letters spell two and six
Example 3
Input: s = "eenono" Output: "11" Why: one, written twice
Constraints
- 1 ≤ length of s ≤ 100,000
- Each letter of s is one of e, f, g, h, i, n, o, r, s, t, u, v, w, x, z
- There is always a set of digit words that uses every letter exactly once
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Remove words one at a timeO(n)
- Solve the counts directlyO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 letters | Verdict |
|---|---|---|---|
| Remove words one at a time | O(n) | Passes; touches letters twice | |
| Solve the counts directly | O(n) | Best; ten subtractions |
n = length of s.
Edge cases to test
- Repeated digits. "eenono" is one twice; the counts give d[1] = 2 and the answer "11".
- No marker letters at all. A mix of only one, three, five, seven and nine has no z, w, u, x or g. Every digit then comes from a subtraction.
- Shared letters. six and seven share s, three and eight share h; subtract the marked digit first.
- Long input. 100,000 letters is still one counting pass.
Common mistakes
- Removing words in plain order 0 to 9, which lets one word take letters another needs.
- Working out nine before five, six and eight are known.
- Returning the digits in the order they were found instead of ascending order.
How to talk through it
- 1Clarify. Is the input always valid? Which letters can appear? Should repeated digits repeat in the output?
- 2Only counts matter. The order of letters is destroyed, so count them.
- 3Find marker letters. z, w, u, x and g each belong to one word. Once those are known, o, h, f, s and i each belong to one remaining word.
- 4Give the cost. O(n) to count, then ten fixed formulas; O(1) space.
- 5Test out loud. Run a single digit, a repeated digit, and a mix with no marker letters.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?