You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the returned string.
Return any permutation of s that satisfies this property.
Example:
Input:
order = "cba"
s = "abcd"
Output:
"cbad"
Explanation:
"a", "b", "c" were sorted in the original order. So "cba" should appear in the returned string. As "d" doesn't exist in order, it can be at any position in the returned string.
order and s are non-empty and order contains only unique characters.s that do not appear in order be handled?
order can appear in any position relative to the characters specified in order, as they have no specified order.order contain characters not present in s?
order may contain characters that do not appear in s.order string?
order and s are non-empty.s. This will help to keep track of the number of occurrences of each character.order string. For each character in order, append it to the result as many times as it appears in s using the Counter created in step 1.order. After processing all characters in order, append any characters in s that do not appear in order.from collections import Counter
def customSortString(order: str, s: str) -> str:
# Step 1: Create a frequency counter for characters in s
count = Counter(s)
# Step 2: Build the result string using the `order` string
result = []
for char in order:
if char in count:
result.append(char * count[char])
del count[char] # remove the character completely
# Step 3: Append remaining characters that were not in `order`
for char, freq in count.items():
result.append(char * freq)
# Join the result list to form the final string
return ''.join(result)
# Example usage
order = "cba"
s = "abcd"
print(customSortString(order, s)) # Output: "cbad"
s takes O(n), where n is the length of s.order string and constructing the result substring for each character present in order takes O(m * freq) where m is the length of order and freq is the average frequency of characters in s. Since freq can be considered as a constant, this step effectively takes O(m).order and appending them to the result string takes O(n - m), where n - m is the count of characters not in order.Therefore, the overall time complexity of the solution is O(n + m) where n is the length of s and m is the length of order.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?