Solution: Custom Sort String
Let's solve the Custom Sort String problem using the Hash Maps pattern.
We'll cover the following
Statement
Given two strings, order
and s
, where all characters in order
are unique and arranged in a custom order, return any permutation of s
that satisfies the following condition:
The characters in the permuted s
should appear in the same relative order as they do in order
. Specifically, if a character x
appears before a character y
in order
, then x
must also appear before y
in the permuted string.
Constraints:
order.length
s.length
order
ands
consist of lowercase English letters.All the characters of
order
are unique.
Solution
An optimal way for solving this problem is to first count the occurrences of each character in s
using a hash map. Then, iterate through the characters in order
, appending as many occurrences of each character to the result string based on its frequency in s
. Finally, append any remaining characters from s
that were not in order
to the result string.
Using the above intuition, the solution can be implemented as follows:
Create a hash map,
frequencies
, to store the count of each character ins
. Here, the key is the character itself and the value is the number of times it appears ins
.Iterate through
s
and updatefrequencies
with the count of occurrences of each character.Define
result
to build the final string.For each character
c
inorder
, if it's present infrequencies
, append it toresult
as many times as its recorded frequency. After that, remove it fromfrequencies
.After processing all characters in
order
, loop through the remaining characters infrequencies
. For each character and its count, append it toresult
.Return
result
which represents the permuteds
satisfying the given condition.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.