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 required result is determined by two facts: each character must appear exactly as many times as it appears in s, and characters mentioned in order must appear in that sequence. You do not need to compare pairs of characters or decide where each occurrence goes individually. Count the available copies first, then consume those counts in the order required by order.
After processing order, any counts left belong to characters that order never mentioned. Those characters have no relative restriction, so appending them in alphabetic order is valid. The count array acts like a set of buckets: every append removes one character from its bucket, which guarantees that the output neither loses nor invents occurrences.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n + m) | The first scan counts each character of s once, the order scan processes each character of order once, and the final scan checks 26 fixed buckets while each remaining occurrence is appended exactly once. |
| Space | O(1) extra | The count array always has 26 entries, regardless of n or m. The returned string is required output and is excluded from the extra-space bound. |
#include <string>
using namespace std;
class Solution {
public:
string customSortString(string order, string s) {
int cnt[26] = {0};
for (char c : s) {
cnt[c - 'a']++;
}
string ans;
for (char c : order) {
while (cnt[c - 'a']-- > 0) {
ans.push_back(c);
}
}
for (int i = 0; i < 26; i++) {
while (cnt[i]-- > 0) {
ans.push_back('a' + i);
}
}
return ans;
}
};The condition in each while loop is deliberately tied to decrementing the count. A bucket with count 3 appends its character three times and ends at -1 after the failed condition check, but it can never append a fourth copy. By the time the final alphabet scan begins, every character mentioned in order has been fully consumed, so only unconstrained characters remain.