Date and Time: Dec 4, 2024, 23:13 (EST)
Link: https://leetcode.com/problems/custom-sort-string
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 permuted string.
Return any permutation of s that satisfies this property.
Example 1:
Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation:
"a","b","c"appear in order, so the order of"a","b","c"should be"c","b", and"a".Since
"d"does not appear inorder, it can be at any position in the returned string."dcba","cdba","cbda"are also valid outputs.
Example 2:
Input: order = "bcafg", s = "abcd"
Output: "bcad"
Explanation: The characters
"b","c", and"a"from order dictate the order for the characters ins. The character"d"insdoes not appear inorder, so its position is flexible.Following the order of appearance in
order,"b","c", and"a"fromsshould be arranged as"b","c","a"."d"can be placed at any position since it's not in order. The output"bcad"correctly follows this rule. Other arrangements like"dbca"or"bcda"would also be valid, as long as"b","c","a"maintain their order.
-
1 <= order.length <= 26 -
1 <= s.length <= 200 -
orderandsconsist of lowercase English letters. -
All the characters of
orderare unique.
-
Loop over
sto save each char with their counts intohashmap{}. -
Loop over
orderand check if char exists inhashmap{}, if so, add this charcwith repeated timeshashmap[c]tores(res += c * hashmap[c]). Delete this key-value pair inhashmap{}. -
Loop over
hashmap{}to add all the missing chars with their repeated times tores.
class Solution:
def customSortString(self, order: str, s: str) -> str:
# Loop over s and save each char with counts
# Loop over `order`, if char exists in hashmap, we add this char * counts to res. Delete this key-val entry in hashmap
# Loop over hashmap to add the missing chars into res
# TC: O(n + k), n = len(s), k = len(order), SC: O(n)
hashmap = {}
res = ""
# Calculate each char in s with their frequency
for c in s:
hashmap[c] = hashmap.get(c, 0) + 1
# Follow the order to append chars into res
for c in order:
if c in hashmap:
res += c * hashmap[c]
del hashmap[c]
# Check the missing chars
for key, val in hashmap.items():
res += key * val
return resTime Complexity:
Space Complexity: s