Reconstruct Original Digits from English - Problem

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

The string contains English words for digits like "zero", "one", "two", etc., but the letters are jumbled together. Your task is to figure out which digits are present and return them sorted.

Note: Each digit appears at most once in the input string.

Input & Output

Example 1 — Basic Mixed Digits
$ Input: s = "owtzero"
Output: "02"
💡 Note: The string contains letters for "zero" (z,e,r,o) and "two" (t,w,o). Since we need ascending order, return "02".
Example 2 — Single Digit
$ Input: s = "fviefuro"
Output: "45"
💡 Note: Contains "four" (f,o,u,r) and "five" (f,i,v,e). The shared 'f' appears twice. Result is "45".
Example 3 — Multiple Overlapping
$ Input: s = "nnei"
Output: "9"
💡 Note: Contains "nine" (n,i,n,e). The string has n(2), e(1), i(1) which exactly matches the letters needed for 'nine'. Note that 'one' cannot be formed since there is no 'o' in the input.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only
  • s contains an out-of-order representation of some digits 0-9
  • Each digit appears at most once

Visualization

Tap to expand
Reconstruct Original Digits from English INPUT Jumbled String: s = "owtzero" Individual Letters: o w t z e r o Letter Frequency: o: 2 | w: 1 | t: 1 z: 1 | e: 1 | r: 1 Contains letters from "zero" and "two" mixed together ALGORITHM STEPS 1 Find Unique Letters 'z' only in "zero" 'w' only in "two" Digit | Unique | Word 0 | z | zero 2 | w | two 2 Count Occurrences Found 'z': count[0]++ Found 'w': count[2]++ 3 Remove Used Letters Subtract z,e,r,o for 0 Subtract t,w,o for 2 4 Build Result Sort digits ascending 0, 2 --> "02" FINAL RESULT Identified Digits: 0 "zero" 2 "two" Output (Sorted Ascending): "02" OK - Verified! z+e+r+o = "zero" (0) t+w+o = "two" (2) All letters used! Key Insight: Some digits have unique identifying letters: 'z' in zero, 'w' in two, 'u' in four, 'x' in six, 'g' in eight. Process these first, then use remaining letters to identify other digits. This greedy approach ensures O(n) time complexity where n is the string length. Each digit appears at most once, simplifying counting. TutorialsPoint - Reconstruct Original Digits from English | Optimized Pattern Recognition
Asked in
Google 23 Facebook 18 Microsoft 15
31.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen