GFG App
Open App
Browser
Continue

Reorder characters of a string to valid English representations of digits

Given a string S of length N, consisting of lowercase characters containing reordered English representations of digits [0 – 9], the task is to print those digits in ascending order.

Examples:

Input: S = “fviefuro”
Output: 45
Explanation: The given string can be reshuffled to “fourfive”, Therefore, the digits represented by the strings are 4 and 5.

Input: S = “owoztneoer”
Output: 012
Explanation: The given string can be reshuffled to get “zeroonetwo”, Therefore, the digits represented by the strings are 0, 1 and 2.

Naive Approach: The simplest approach is to generate all permutations of the given string and for each permutation, check if it is possible to find valid digits represented by the string. If found to be true, then print the set of digits in ascending order.

Time Complexity: O(N * N!)
Auxiliary Space: O(1)

Efficient Approach: The idea is based on the observation that some characters only appear in one number.

In ‘zero’, character ‘z’ is unique.
In ‘two’, character ‘w’ is unique.
In ‘four’, character ‘u’ is unique.
In ‘six’, character ‘x’ is unique.
In ‘eight’, character ‘g’ is unique.
In ‘three’, character ‘h’ is unique since word “eight” having character ‘h’ has already been considered.
In ‘one’, character ‘o’ is unique since words having character ‘o’ have already been considered.
In ‘five’, character f’ is unique since word “four” having character ‘f’ has already been considered.
In ‘seven’, character ‘v’ is unique.
In ‘nine’, character ‘i’ is unique since words having character ‘i’ have already been considered.

Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++

 `// C++ program to implement the above approach`   `// Function to construct the original set of digits` `// from the string in ascending order` `#include ` `using` `namespace` `std;`   `string construct_digits(string s)` `{`   `    ``// Store the unique characters` `    ``// corresponding to word and number` `    ``vector<``char``>k = { ``'z'``, ``'w'``, ``'u'``, ``'x'``, ``'g'``,` `                ``'h'``, ``'o'``, ``'f'``, ``'v'``, ``'i'` `};`   `    ``vectorl = { ``"zero"``, ``"two"``, ``"four"``, ``"six"``, ``"eight"``,` `                ``"three"``, ``"one"``, ``"five"``, ``"seven"``, ``"nine"` `};`   `    ``vector<``int``>c = { 0, 2, 4, 6, 8, 3, 1, 5, 7, 9 };`   `    ``// Store the required result` `    ``vector<``int``> ans = {};`   `    ``// Store the frequency of` `    ``// each character of S` `    ``unordered_map<``char``,``int``>d;` `    ``for``(``int` `i = 0; i < s.length(); i++)` `    ``{` `        ``d[s[i]]++;` `    ``}`   `    ``// Traverse the unique characters` `    ``for``(``int` `i = 0; i < k.size(); i++)` `    ``{` `        `  `        ``// Store the count of k[i] in S` `        ``int` `x = 0;` `        ``if` `(d.find(k[i]) != d.end())` `            ``x = d[k[i]];`   `        ``// Traverse the corresponding word` `        ``for``(``int` `j = 0; j < l[i].length(); j++)` `        ``{` `            `  `            ``// Decrement the frequency` `            ``// of characters by x` `            ``if` `(d.find(l[i][j]) != d.end())` `                ``d[l[i][j]]-= x;` `        ``}`   `        ``// Append the digit x times to ans` `        ``for``(``int` `j = 0; j < x; j++)` `            ``ans.push_back(c[i]);` `    ``}`   `    ``// Sort the digits in ascending order` `    ``sort(ans.begin(),ans.end());` `    `  `    ``string res;` `    ``for``(``auto` `x: ans)res+=(x+``'0'``);` `    ``return` `res;` `}`   `// Driver Code` `int` `main()` `{` `  `  `   ``// Given string, s` `   ``string s = ``"fviefuro"``;` `  `  `   ``// Function Call` `   ``cout<<(construct_digits(s));` `}`   `// This code is contributed by shinjanpatra`

Java

 `// Java program to implement the above approach` `import` `java.io.*;` `import` `java.lang.*;` `import` `java.util.*;`   `class` `GFG{`   `// Function to construct the original set of digits` `// from the string in ascending order` `static` `String construct_digits(String s)` `{` `    `  `    ``// Store the unique characters` `    ``// corresponding to word and number` `    ``char``[] k = { ``'z'``, ``'w'``, ``'u'``, ``'x'``, ``'g'``,` `                 ``'h'``, ``'o'``, ``'f'``, ``'v'``, ``'i'` `};`   `    ``String[] l = { ``"zero"``, ``"two"``, ``"four"``, ``"six"``, ``"eight"``,` `                   ``"three"``, ``"one"``, ``"five"``, ``"seven"``, ``"nine"` `};`   `    ``int``[] c = { ``0``, ``2``, ``4``, ``6``, ``8``, ``3``, ``1``, ``5``, ``7``, ``9` `};`   `    ``// Store the required result` `    ``List ans = ``new` `ArrayList<>();`   `    ``// Store the frequency of` `    ``// each character of S` `    ``HashMap d = ``new` `HashMap<>();` `    ``for``(``int` `i = ``0``; i < s.length(); i++)` `    ``{` `        ``d.put(s.charAt(i),` `              ``d.getOrDefault(s.charAt(i), ``0``) + ``1``);` `    ``}`   `    ``// Traverse the unique characters` `    ``for``(``int` `i = ``0``; i < k.length; i++)` `    ``{` `        `  `        ``// Store the count of k[i] in S` `        ``int` `x = ``0``;` `        ``if` `(d.containsKey(k[i]))` `            ``x = d.get(k[i]);`   `        ``// Traverse the corresponding word` `        ``for``(``int` `j = ``0``; j < l[i].length(); j++)` `        ``{` `            `  `            ``// Decrement the frequency` `            ``// of characters by x` `            ``if` `(d.containsKey(l[i].charAt(j)))` `                ``d.put(l[i].charAt(j),` `                ``d.get(l[i].charAt(j)) - x);` `        ``}`   `        ``// Append the digit x times to ans` `        ``for``(``int` `j = ``0``; j < x; j++)` `            ``ans.add(c[i]);` `    ``}`   `    ``// Sort the digits in ascending order` `    ``Collections.sort(ans);` `    ``String str = ``""``;` `    ``for``(``int` `val : ans)` `        ``str += val;`   `    ``return` `str;` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given string, s` `    ``String s = ``"fviefuro"``;`   `    ``// Function Call` `    ``System.out.println(construct_digits(s));` `}` `}`   `// This code is contributed by Kingash`

Python3

 `# Python program to implement the above approach` `from` `collections ``import` `Counter`   `# Function to construct the original set of digits` `# from the string in ascending order` `def` `construct_digits(s):` `  `  `    ``# Store the unique characters` `    ``# corresponding to word and number` `    ``k ``=` `[``"z"``, ``"w"``, ``"u"``, ``"x"``, ``"g"``, ` `         ``"h"``, ``"o"``, ``"f"``, ``"v"``, ``"i"``]`   `    ``l ``=` `[``"zero"``, ``"two"``, ``"four"``, ``"six"``, ``"eight"``,` `         ``"three"``, ``"one"``, ``"five"``, ``"seven"``, ``"nine"``]`   `    ``c ``=` `[``0``, ``2``, ``4``, ``6``, ``8``, ``3``, ``1``, ``5``, ``7``, ``9``]` `    `  `    ``# Store the required result` `    ``ans ``=` `[]` `    `  `    ``# Store the frequency of` `    ``# each character of S` `    ``d ``=` `Counter(s)`   `    ``# Traverse the unique characters ` `    ``for` `i ``in` `range``(``len``(k)):`   `        ``# Store the count of k[i] in S` `        ``x ``=` `d.get(k[i], ``0``)` `        `  `        ``# Traverse the corresponding word` `        ``for` `j ``in` `range``(``len``(l[i])):` `              `  `            ``# Decrement the frequency` `            ``# of characters by x` `            ``d[l[i][j]]``-``=` `x` `            `  `        ``# Append the digit x times to ans` `        ``ans.append(``str``(c[i])``*``x)`   `    ``# Sort the digits in ascending order` `    ``ans.sort()`   `    ``return` `"".join(ans)`   `# Driver Code`   `# Given string, s` `s ``=` `"fviefuro"`   `# Function Call` `print``(construct_digits(s))`

C#

 `// C# program to implement the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG{`   `// Function to construct the original set of digits` `// from the string in ascending order` `static` `string` `construct_digits(``string` `s)` `{` `    `  `    ``// Store the unique characters` `    ``// corresponding to word and number` `    ``char``[] k = { ``'z'``, ``'w'``, ``'u'``, ``'x'``, ``'g'``,` `                 ``'h'``, ``'o'``, ``'f'``, ``'v'``, ``'i'` `};`   `    ``string``[] l = { ``"zero"``, ``"two"``, ``"four"``, ``"six"``, ``"eight"``,` `                   ``"three"``, ``"one"``, ``"five"``, ``"seven"``, ``"nine"` `};`   `    ``int``[] c = { 0, 2, 4, 6, 8, 3, 1, 5, 7, 9 };`   `    ``// Store the required result` `    ``List<``string``> ans = ``new` `List<``string``>();`   `    ``// Store the frequency of` `    ``// each character of S` `    ``Dictionary<``char``, ` `               ``int``> d = ``new` `Dictionary<``char``,` `                                       ``int``>();` `    ``for``(``int` `i = 0; i < s.Length; i++) ` `    ``{` `        ``if` `(!d.ContainsKey(s[i]))` `            ``d[s[i]] = 0;` `            `  `        ``d[s[i]] += 1;` `    ``}`   `    ``// Traverse the unique characters` `    ``for``(``int` `i = 0; i < k.Length; i++)` `    ``{` `        `  `        ``// Store the count of k[i] in S` `        ``int` `x = 0;` `        ``if` `(d.ContainsKey(k[i]))` `            ``x = d[k[i]];`   `        ``// Traverse the corresponding word` `        ``for``(``int` `j = 0; j < l[i].Length; j++)` `        ``{` `            `  `            ``// Decrement the frequency` `            ``// of characters by x` `            ``if` `(d.ContainsKey(l[i][j]))` `                ``d[l[i][j]] -= x;` `        ``}` `        `  `        ``// Append the digit x times to ans` `        ``ans.Add(((c[i]) * x).ToString());` `    ``}` `    `  `    ``// Sort the digits in ascending order` `    ``ans.Sort();`   `    ``string` `str = (String.Join(``""``, ans.ToArray()));` `    ``return` `str.Replace(``"0"``, ``""``);` `}`   `// Driver Code` `public` `static` `void` `Main(``string``[] args)` `{` `    `  `    ``// Given string, s` `    ``string` `s = ``"fviefuro"``;`   `    ``// Function Call` `    ``Console.WriteLine(construct_digits(s));` `}` `}`   `// This code is contributed by ukasp`

Javascript

 ``

Output:

`45`

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up