Custom Sort String

Reorder `s` so its characters follow the custom alphabet `order` first.

Medium
Time O(N + 26) Space O(1)
LeetCode
3 min read
hash-map sorting strings

Problem#

Given strings order and s, return any permutation of s such that characters appearing in order come first, in the same relative order as order. Characters not in order may appear in any position.

Examples#

  • order = "cba", s = "abcd""cbad" (or "dcba", etc.).
  • order = "bcafg", s = "abcd""bcad".

Constraints#

  • 1 <= order.length <= 26, 1 <= s.length <= 200. Both contain only lowercase letters.

Hints#

Hint
Count letters in s. Emit order letters first (decrementing counts), then the remaining letters in any order.

Approach#

Counter array cnt[26] over s. For each char in order (in order), append it cnt[c] times and zero its count. Then append any remaining letters with non-zero counts (their order is unconstrained).

Solution#

Custom Sort String
class Solution {
public:
string customSortString(string order, string s) {
int cnt[26] = {0};
for (char c : s) ++cnt[c - 'a'];
string ans;
ans.reserve(s.size());
for (char c : order) {
int idx = c - 'a';
ans.append(cnt[idx], c);
cnt[idx] = 0;
}
for (int i = 0; i < 26; ++i) ans.append(cnt[i], 'a' + i);
return ans;
}
};

Editorial#

Linear emission beats comparator-based sorting (O(N log N)) for short alphabets — we know the rank of each letter from order’s position. The two-phase emit (ordered then leftover) handles letters outside order cleanly.

Complexity#

  • Time: O(N + 26).
  • Space: O(1) extra.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.