Custom Sort String
Custom Sort String is a medium arrays & hashing problem solved with the hashing pattern.
The best approach, optimal (count, then write), runs in O(n + k) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from collect letter by letter up.
Problem
You are given two strings, order and s. The string order lists some lowercase letters, each at most once, and it defines a new ranking of those letters: a letter that appears earlier in order ranks before a letter that appears later.
Rearrange the characters of s so that it follows this ranking. Whenever two letters x and y both appear in order and x comes before y there, every x in the result must come before every y. Letters of s that do not appear in order have no rank, so they may be placed anywhere.
Return any rearrangement of s that satisfies the rule. It must use every character of s exactly once.
Examples
Example 1
- Input
order = "kxa", s = "taxkk"- Output
"kkxat"- Why
- In order, k comes first, then x, then a. So both k's go to the front, then the x, then the a. The letter t is not in order, so it may sit anywhere; here it is placed at the end.
Example 2
- Input
order = "zyx", s = "xyzabc"- Output
"zyxabc"- Why
- The letters z, y and x must appear in that order. The letters a, b and c are free, so answers like "azbycx" are also accepted.
Example 3
- Input
order = "q", s = "pqrq"- Output
"qqpr"- Why
- Only q is ranked, and it has no other ranked letter to compete with, so any rearrangement of the four letters is valid. One of them is shown.
Constraints
1 <= order.length <= 261 <= s.length <= 10^5orderandscontain only lowercase English letters.- All letters of
orderare different.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Collect letter by letter | O(k · n) | O(n) |
| Sort by rank | O(n log n) | O(n) |
| Optimal (count, then write) | O(n + k) | O(n) |
1Collect letter by letter
O(k · n)For each of the k letters of order (at most 26) we scan all n characters of s, plus one last scan.O(n)The answer itself takes n characters; the mark table has a fixed 26 entries.Walk through order one letter at a time. For each letter, scan the whole of s and copy every match into the answer. After that, scan s once more and copy every letter that order never mentions.
- Keep a table inOrder[26] that marks the letters seen in order.
- For each letter c of order, mark it, then scan s and append every character equal to c.
- Finally scan s again and append each character whose letter is not marked.
- The ranked letters come out in the order of order, and the rest follow them.
class Solution {
public String customSortString(String order, String s) {
boolean[] inOrder = new boolean[26];
StringBuilder sb = new StringBuilder();
for (char c : order.toCharArray()) {
inOrder[c - 'a'] = true;
for (char x : s.toCharArray()) {
if (x == c) sb.append(x);
}
}
for (char x : s.toCharArray()) {
if (!inOrder[x - 'a']) sb.append(x);
}
return sb.toString();
}
}class Solution:
def customSortString(self, order: str, s: str) -> str:
in_order = [False] * 26
out = []
for c in order:
in_order[ord(c) - ord('a')] = True
for x in s:
if x == c:
out.append(x)
for x in s:
if not in_order[ord(x) - ord('a')]:
out.append(x)
return "".join(out)class Solution {
public:
string customSortString(string order, string s) {
vector<bool> inOrder(26, false);
string out;
for (char c : order) {
inOrder[c - 'a'] = true;
for (char x : s) {
if (x == c) out.push_back(x);
}
}
for (char x : s) {
if (!inOrder[x - 'a']) out.push_back(x);
}
return out;
}
};function customSortString(order, s) {
const inOrder = new Array(26).fill(false);
const out = [];
for (const c of order) {
inOrder[c.charCodeAt(0) - 97] = true;
for (const x of s) {
if (x === c) out.push(x);
}
}
for (const x of s) {
if (!inOrder[x.charCodeAt(0) - 97]) out.push(x);
}
return out.join("");
}2Sort by rank
O(n log n)Building the rank table is O(k); the sort of n characters is O(n log n).O(n)The array of characters being sorted, plus the answer.Turn order into a rank table: rank of a letter is its index in order, and every letter that is not in order gets rank 26, after all ranked letters. Then sort the characters of s by rank. Equal ranks may land in any order, which the problem allows.
- Fill rank[26] with 26, then set rank[order[i]] = i for every position i.
- Copy the characters of s into an array of boxed characters (or a list).
- Sort that array with a comparator that compares ranks.
- Join the sorted characters into the answer.
class Solution {
public String customSortString(String order, String s) {
int[] rank = new int[26];
Arrays.fill(rank, 26);
for (int i = 0; i < order.length(); i++) rank[order.charAt(i) - 'a'] = i;
Character[] chars = new Character[s.length()];
for (int i = 0; i < s.length(); i++) chars[i] = s.charAt(i);
Arrays.sort(chars, (a, b) -> rank[a - 'a'] - rank[b - 'a']);
StringBuilder sb = new StringBuilder();
for (char c : chars) sb.append(c);
return sb.toString();
}
}class Solution:
def customSortString(self, order: str, s: str) -> str:
rank = [26] * 26
for i, c in enumerate(order):
rank[ord(c) - ord('a')] = i
return "".join(sorted(s, key=lambda c: rank[ord(c) - ord('a')]))class Solution {
public:
string customSortString(string order, string s) {
vector<int> rank(26, 26);
for (int i = 0; i < (int)order.size(); i++) rank[order[i] - 'a'] = i;
sort(s.begin(), s.end(), [&](char a, char b) { return rank[a - 'a'] < rank[b - 'a']; });
return s;
}
};function customSortString(order, s) {
const rank = new Array(26).fill(26);
for (let i = 0; i < order.length; i++) rank[order.charCodeAt(i) - 97] = i;
const chars = s.split("");
chars.sort((a, b) => rank[a.charCodeAt(0) - 97] - rank[b.charCodeAt(0) - 97]);
return chars.join("");
}3Optimal (count, then write)
O(n + k)One pass over s to count, one pass over order, and a fixed 26-step pass; every character of s is written exactly once.O(n)The count table has 26 entries; only the answer itself grows with n.The answer only depends on how many times each letter appears in s, not where. Count the 26 letters in one pass. Then write each letter of order as many times as it was counted, clearing its count, and finally write whatever counts are left, in any order (here a to z).
- count[26]: one pass over s adds one for each character.
- For each letter c of order, append c count[c] times and set count[c] to zero.
- For each letter from a to z, append it count times. Only letters missing from order still have a count.
- Return the built string.
class Solution {
public String customSortString(String order, String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < order.length(); i++) {
char c = order.charAt(i);
while (count[c - 'a'] > 0) {
sb.append(c);
count[c - 'a']--;
}
}
for (char c = 'a'; c <= 'z'; c++) {
while (count[c - 'a'] > 0) {
sb.append(c);
count[c - 'a']--;
}
}
return sb.toString();
}
}class Solution:
def customSortString(self, order: str, s: str) -> str:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
out = []
for c in order:
idx = ord(c) - ord('a')
out.append(c * count[idx])
count[idx] = 0
for idx in range(26):
if count[idx] > 0:
out.append(chr(ord('a') + idx) * count[idx])
return "".join(out)class Solution {
public:
string customSortString(string order, string s) {
vector<int> count(26, 0);
for (char c : s) count[c - 'a']++;
string out;
for (char c : order) {
while (count[c - 'a'] > 0) {
out.push_back(c);
count[c - 'a']--;
}
}
for (char c = 'a'; c <= 'z'; c++) {
while (count[c - 'a'] > 0) {
out.push_back(c);
count[c - 'a']--;
}
}
return out;
}
};function customSortString(order, s) {
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) count[s.charCodeAt(i) - 97]++;
const out = [];
for (const c of order) {
const idx = c.charCodeAt(0) - 97;
out.push(c.repeat(count[idx]));
count[idx] = 0;
}
for (let idx = 0; idx < 26; idx++) {
if (count[idx] > 0) out.push(String.fromCharCode(97 + idx).repeat(count[idx]));
}
return out.join("");
}Edge cases to test
- No letter of s appears in order (any rearrangement of s is fine, including s itself)
- Every letter of s appears in order
- s is a single letter
- A letter of order that never appears in s
- Many copies of the same letter, which must all stay together in their ranked slot
- order holds all 26 letters, so the whole answer is fixed
Hints
Hint 1
Give each letter of order a rank: its position in order. Letters that are not in order can share one rank after all the others.
Hint 2
Sorting by that rank works, but you only have 26 possible letters. Do you need a real sort at all?
Hint 3
Count how many times each letter appears in s. Then write the letters of order, each repeated by its count, and finish with the leftover letters.
FAQ
What is the best time complexity for Custom Sort String?
Optimal (count, then write) runs in O(n + k) time and O(n) extra space. One pass over s to count, one pass over order, and a fixed 26-step pass; every character of s is written exactly once.
Which pattern does Custom Sort String use?
It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.
Is there a brute force solution for Custom Sort String?
Yes. Collect letter by letter takes O(k · n) time and O(n) space. Walk through order one letter at a time.
Which edge cases should I test for Custom Sort String?
No letter of s appears in order (any rearrangement of s is fine, including s itself); Every letter of s appears in order; s is a single letter; A letter of order that never appears in s; Many copies of the same letter, which must all stay together in their ranked slot; order holds all 26 letters, so the whole answer is fixed.