
Custom Sort String (medium)
Problem Statement
You are given two strings pattern and text. It is given that all characters of the pattern string are unique.
Rearrange the characters of the text string based on the characters' order in pattern string. In other words, if a character a occurs before a character b in the pattern string, then a should occur before b in the output string.
Characters in text that do not appear in pattern should be appended at the end of the rearranged string in their original order.
Examples
-
Example 1:
- Input:
pattern = "xy", text = "yyzx" - Expected Output:
"xyyz" - Justification: In 'pattern', the order is 'x', 'y'. In the
text, 'x' appears once, 'y' twice, and 'z' doesn't appear. So, we putzat the end of the string. Thus, the output string isxzyy.
- Input:
-
Example 2:
- Input:
pattern = "abc", text = "aabbcc" - Expected Output:
"aabbcc" - Justification: Here, the 'text' already follows the order 'a', 'b', 'c' as specified in 'pattern', so the order remains 'aabbcc'.
- Input:
-
Example 3:
- Input:
pattern = "mno", text = "onomon" - Expected Output:
"mnnooo" - Justification: According to 'pattern', 'm' comes first, then 'n', then 'o'. Rearranging 'text' in this order results in 'm' once, 'n' twice, followed by 'o' thrice, hence 'mnnooo'.
- Input:
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory