Custom Sort String (LeetCode 791): Solution and Explanation
Rearrange the characters of s so that letters listed in order appear in that sequence. Letters that are not in order can go anywhere. Any valid arrangement is accepted.
Intuition
The rule only talks about letters that appear in order: all copies of an earlier letter must come before all copies of a later one. That means every copy of the same letter can be written as one block.
So you do not need to compare characters at all. Count how many of each letter s has, then write the blocks in the sequence order gives.
Letters missing from order have no rank. Once the ranked blocks are written, whatever is still counted can be appended in any order and the result is still valid.
With only 26 lowercase letters, the counts fit in a fixed array, so the whole thing is linear.
Approach: Counting and writing in rank order
- Create an array
countof 26 zeros and count every character ofs. - For each character
choforder, appendchrepeatedcount[ch]times to the output and setcount[ch] = 0. - Walk the 26 letters and append any that still have a non-zero count (they are the letters not in
order). - Return the joined output.
Step-by-step example
order = "cba", s = "abcd"
- Count s: a = 1, b = 1, c = 1, d = 1.
- order[0] = 'c': write one c. Output "c".
- order[1] = 'b': write one b. Output "cb".
- order[2] = 'a': write one a. Output "cba".
- Only d is left, and it has no rank, so append it: "cbad".
Code: Python, Java, C++
1class Solution:
2 def customSortString(self, order: str, s: str) -> str:
3 count = [0] * 26
4 for ch in s:
5 count[ord(ch) - 97] += 1
6 out = []
7 for ch in order:
8 k = ord(ch) - 97
9 out.append(ch * count[k])
10 count[k] = 0
11 for k in range(26):
12 out.append(chr(97 + k) * count[k])
13 return ''.join(out)1class Solution {
2 public String customSortString(String order, String s) {
3 int[] count = new int[26];
4 for (char ch : s.toCharArray()) {
5 count[ch - 'a']++;
6 }
7 StringBuilder sb = new StringBuilder();
8 for (char ch : order.toCharArray()) {
9 sb.append(String.valueOf(ch).repeat(count[ch - 'a']));
10 count[ch - 'a'] = 0;
11 }
12 for (int k = 0; k < 26; k++) {
13 sb.append(String.valueOf((char) ('a' + k)).repeat(count[k]));
14 }
15 return sb.toString();
16 }
17}1class Solution {
2public:
3 string customSortString(string order, string s) {
4 int count[26] = {0};
5 for (char ch : s) {
6 count[ch - 'a']++;
7 }
8 string out;
9 for (char ch : order) {
10 out.append(count[ch - 'a'], ch);
11 count[ch - 'a'] = 0;
12 }
13 for (int k = 0; k < 26; k++) {
14 out.append(count[k], (char) ('a' + k));
15 }
16 return out;
17 }
18};Time and space complexity
O(|order| + |s|)
Counting reads s once, writing visits each order letter once and each character of s is written once.
O(1)
Apart from the output string, only 26 counters are stored.
Other approaches
Sort with a custom key (time O(|s| log |s|), space O(|s|))
Build a rank map from order, give letters not in order a rank such as 26, and sort the characters of s by rank. Short to write, but it costs a comparison sort.
Bucket by rank (time O(|order| + |s|), space O(|s|))
Create 27 buckets, one per rank plus one for unranked letters, push each character of s into its bucket and concatenate. Same complexity as counting, with lists instead of counters.
Common mistakes
- Dropping the letters that are not in order. They still have to appear in the output, the same number of times as in s.
- Forgetting to zero a count after writing its block, so the final pass writes those letters a second time.
- Assuming the expected output is unique. Unranked letters can be anywhere, so a correct answer may differ from the example output.
Frequently asked questions
Why does any position work for letters not in order?
The rule only compares pairs of letters that both appear in order. A letter outside order is never part of such a pair, so moving it does not break anything.
Can order contain letters that s does not have?
Yes. Their count is zero, so writing them adds nothing. The walk just skips past them.
Is a comparison sort wrong here?
No, sorting by rank gives a valid answer. Counting is simply faster, because the alphabet has a fixed size of 26.