Leetcode 791: Custom Sort String

grid47
grid47
Exploring patterns and algorithms
Aug 19, 2024 5 min read

A string being sorted according to custom rules, with each valid sorting step glowing softly.
Solution to LeetCode 791: Custom Sort String Problem

You are given a string order that specifies a custom order of characters, and a string s that contains the characters you need to permute. The task is to rearrange the characters of s so that they follow the order specified in the string order. If a character appears in order, it must appear in s in the same relative order. Any characters from s that don’t appear in order can be arranged in any position.
Problem
Approach
Steps
Complexity
Input: The input consists of two strings: order and s.
Example: order = 'zyx', s = 'abcxyz'
Constraints:
• 1 <= order.length <= 26
• 1 <= s.length <= 200
• order and s consist of lowercase English letters.
• All characters in order are unique.
Output: Return a string that is a permutation of s, where the characters are arranged according to the order given by the string order. If a character does not appear in order, it can appear in any position.
Example: Output: 'zyxcba'
Constraints:
• The output should be a valid permutation of the characters of s.
Goal: The goal is to permute the string s based on the order of characters provided in order.
Steps:
• Create a mapping of each character in order to its position.
• Sort the string s using this mapping to ensure that characters in s appear in the same order as in order.
• Characters not in order can be placed in any position in s.
Goal: Ensure that the input strings order and s meet the specified constraints.
Steps:
• The characters in order are unique and consist of lowercase letters.
• The length of order is between 1 and 26, and the length of s is between 1 and 200.
Assumptions:
• The input strings are valid, and characters in order appear only once.
Input: Input: order = 'abc', s = 'bca'
Explanation: The characters 'a', 'b', and 'c' must be arranged in the order specified by order. Therefore, the output should be 'abc'.

Input: Input: order = 'zyx', s = 'abcxyz'
Explanation: The characters 'x', 'y', and 'z' must appear in the order 'z', 'y', 'x' as per order, while 'a', 'b', and 'c' can appear in any order.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus