Skip to content

Commit aa0ecaf

Browse files
authored
791 - Custom Sort String.md
1 parent 1247399 commit aa0ecaf

File tree

1 file changed

+140
-0
lines changed

1 file changed

+140
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
---
2+
id: custom-sort-string
3+
title: Custom Sort String
4+
sidebar_label: 791 - Custom Sort String
5+
tags: [String, Sorting]
6+
description: Given two strings, sort the second string based on the custom order defined by the first string.
7+
---
8+
9+
## Problem Statement
10+
11+
### Problem Description
12+
13+
You are given two strings `order` and `s`. All the characters in `order` are unique and were sorted in some custom order previously.
14+
15+
Permute the characters of `s` so that they match the order in which characters appear in `order`. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
16+
17+
Return any permutation of `s` that satisfies this property.
18+
19+
### Example
20+
21+
**Example 1:**
22+
```
23+
Input: order = "cba", s = "abcd"
24+
Output: "cbad"
25+
```
26+
**Explanation:** "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
27+
28+
29+
**Example 2:**
30+
```
31+
Input: order = "bcafg", s = "abcd"
32+
Output: "bcad"
33+
```
34+
**Explanation:** The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.
35+
36+
37+
### Constraints
38+
39+
- 1 <= `order.length` <= 26
40+
- 1 <= `s.length` <= 200
41+
- `order` and `s` consist of lowercase English letters.
42+
- All the characters in `order` are unique.
43+
44+
## Solution
45+
46+
### Intuition
47+
48+
To solve this problem, we need to rearrange the characters of string `s` according to the custom order defined by the string `order`. The key steps involve:
49+
50+
1. **Counting Characters in `s`:** Use a frequency map (or dictionary) to count the occurrences of each character in `s`.
51+
2. **Arranging Characters According to `order`:** Iterate over `order` and construct the result string by adding characters from `s` in the sequence specified by `order`.
52+
3. **Adding Remaining Characters:** After processing `order`, append the remaining characters in `s` that are not present in `order`.
53+
54+
### Time and Space Complexity
55+
56+
- **Time Complexity:** The time complexity is $O(n + m)$, where $n$ is the length of `s` and $m$ is the length of `order`. This includes counting the frequency of characters in `s` and constructing the output string.
57+
58+
- **Space Complexity:** The space complexity is $O(n + m)$ due to storing the frequency map and the output string.
59+
60+
### Code
61+
62+
#### C++
63+
64+
```cpp
65+
class Solution {
66+
public:
67+
string customSortString(string order, string s) {
68+
unordered_map<char, int> count;
69+
for (char c : s) {
70+
count[c]++;
71+
}
72+
73+
string result;
74+
for (char c : order) {
75+
if (count.count(c)) {
76+
result.append(count[c], c);
77+
count.erase(c);
78+
}
79+
}
80+
81+
for (const auto& [c, freq] : count) {
82+
result.append(freq, c);
83+
}
84+
85+
return result;
86+
}
87+
};
88+
```
89+
#### Python
90+
```python
91+
class Solution:
92+
def customSortString(self, order: str, s: str) -> str:
93+
count = {}
94+
for char in s:
95+
count[char] = count.get(char, 0) + 1
96+
97+
result = []
98+
for char in order:
99+
if char in count:
100+
result.append(char * count[char])
101+
del count[char]
102+
103+
for char, freq in count.items():
104+
result.append(char * freq)
105+
106+
return ''.join(result)
107+
```
108+
#### Java
109+
```java
110+
class Solution {
111+
public String customSortString(String order, String s) {
112+
Map<Character, Integer> count = new HashMap<>();
113+
for (char c : s.toCharArray()) {
114+
count.put(c, count.getOrDefault(c, 0) + 1);
115+
}
116+
117+
StringBuilder result = new StringBuilder();
118+
for (char c : order.toCharArray()) {
119+
if (count.containsKey(c)) {
120+
int freq = count.get(c);
121+
for (int i = 0; i < freq; i++) {
122+
result.append(c);
123+
}
124+
count.remove(c);
125+
}
126+
}
127+
128+
for (Map.Entry<Character, Integer> entry : count.entrySet()) {
129+
char c = entry.getKey();
130+
int freq = entry.getValue();
131+
for (int i = 0; i < freq; i++) {
132+
result.append(c);
133+
}
134+
}
135+
136+
return result.toString();
137+
}
138+
}
139+
```
140+
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.

0 commit comments

Comments
 (0)