Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The input is a collection of complete digit words with their letters shuffled together. Order is therefore irrelevant; the useful information is how many times each letter appears. If a letter belongs to only one digit word, its frequency directly tells you how many copies of that digit are present.
Five letters have this property immediately: z identifies zero, w identifies two, u identifies four, x identifies six, and g identifies eight. Once you know those counts, subtract every letter contributed by those words. The remaining frequencies then expose one unique letter for each remaining digit: o for one, t for three, f for five, s for seven, and i for nine. Finally, emit each digit as many times as its count, from 0 through 9.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | Building the frequency array reads each input character once. The later scans touch only the fixed ten digit words and append exactly n output characters, so their total work is linear in the input size. |
| Space | O(1) extra | The frequency array, digit counts, and ten fixed word descriptions use constant space. The returned string contains n characters but is required output and is excluded from the extra-space bound; the bound stays O(1) even for the worst input size. |
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string originalDigits(string s) {
vector<int> cnt(26, 0);
for (char c : s) {
cnt[c - 'a']++;
}
vector<int> out(10, 0);
out[0] = cnt['z' - 'a'];
out[2] = cnt['w' - 'a'];
out[4] = cnt['u' - 'a'];
out[6] = cnt['x' - 'a'];
out[8] = cnt['g' - 'a'];
string digits[] = {"zero", "two", "four", "six", "eight"};
int nums[] = {0, 2, 4, 6, 8};
for (int i = 0; i < 5; i++) {
for (char c : digits[i]) {
cnt[c - 'a'] -= out[nums[i]];
}
}
out[1] = cnt['o' - 'a'];
out[3] = cnt['t' - 'a'];
out[5] = cnt['f' - 'a'];
out[7] = cnt['s' - 'a'];
out[9] = cnt['i' - 'a'];
string result;
for (int digit = 0; digit <= 9; digit++) {
result.append(out[digit], '0' + digit);
}
return result;
}
};The subtraction loop is the bridge between the two groups of digits. For example, every discovered zero consumes one z, one e, one r, and one o from the frequency array. After all five unique-letter digits are removed, the remaining count of o cannot come from zero, two, four, six, or eight, so it is exactly the number of ones. The same reasoning applies to the other four residual letters.