Custom Sort String
You're given two strings, order and s. Every character in order is unique, and order defines a custom sort order. Rearrange the characters of s so they follow that order: if x comes before y in order, every x must come before every y in the result.
Characters of s that don't appear in order go at the end, in the same order they appear in s.
Example 1
Input: order = "cba", s = "abcd" Output: "cbad"
c, b and a follow the custom order. d isn't in order, so it goes at the end.
Example 2
Input: order = "bcafg", s = "abcd" Output: "bcad"
f and g are in order but not in s, so they don't appear in the result.
Constraints
1 <= order.length <= 261 <= s.length <= 200orderandscontain only lowercase English letters, and every character oforderis unique.
Approach
You could sort s with a comparator that ranks characters by their position in order, which takes O(n log n) time. Counting does it in linear time. Count every character of s, then build the result by walking through order and writing out each character as many times as it was counted. That places all the ordered characters correctly.
The characters that aren't in order still need to go at the end in their original order, so make a second pass over s and append each one you find.
Steps
- Count how many times each character appears in
s. - For each character in
order, append it to the result as many times as it was counted. - Walk through
sand append every character that isn't inorder. - Return the result.
from collections import Counter
def custom_sort_string(order: str, s: str) -> str:
counts = Counter(s)
result = []
for ch in order:
result.append(ch * counts[ch]) # every copy of ch, in order's position
in_order = set(order)
for ch in s:
if ch not in in_order:
result.append(ch) # the rest keep their original order
return "".join(result)Complexity
- Time:
O(n + m), wherenis the length ofsandmis the length oforder. - Space:
O(1)for the counts, since there are only 26 letters, not counting the output.
Common mistakes
- Writing each character of
orderonce instead of once per occurrence.order = "a",s = "aaa"should giveaaa. - Dropping characters that aren't in
order. They still belong in the result, after the others. - Adding the leftover characters from the counts in alphabetical order. They should keep the order they have in
s.
Coded the solution using this approach that is frequency table and counting. it is Leetcode 791