Skip to content

Commit e492a73

Browse files
authored
Merge pull request #4181 from revanth1718/main
Add solution to LC problem 791
2 parents 49a4e02 + a200784 commit e492a73

File tree

1 file changed

+141
-0
lines changed

1 file changed

+141
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
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+
45+
## Solution
46+
47+
### Intuition
48+
49+
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:
50+
51+
1. **Counting Characters in `s`:** Use a frequency map (or dictionary) to count the occurrences of each character in `s`.
52+
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`.
53+
3. **Adding Remaining Characters:** After processing `order`, append the remaining characters in `s` that are not present in `order`.
54+
55+
### Time and Space Complexity
56+
57+
- **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.
58+
59+
- **Space Complexity:** The space complexity is $O(n + m)$ due to storing the frequency map and the output string.
60+
61+
### Code
62+
63+
#### C++
64+
65+
```cpp
66+
class Solution {
67+
public:
68+
string customSortString(string order, string s) {
69+
unordered_map<char, int> count;
70+
for (char c : s) {
71+
count[c]++;
72+
}
73+
74+
string result;
75+
for (char c : order) {
76+
if (count.count(c)) {
77+
result.append(count[c], c);
78+
count.erase(c);
79+
}
80+
}
81+
82+
for (const auto& [c, freq] : count) {
83+
result.append(freq, c);
84+
}
85+
86+
return result;
87+
}
88+
};
89+
```
90+
#### Python
91+
```python
92+
class Solution:
93+
def customSortString(self, order: str, s: str) -> str:
94+
count = {}
95+
for char in s:
96+
count[char] = count.get(char, 0) + 1
97+
98+
result = []
99+
for char in order:
100+
if char in count:
101+
result.append(char * count[char])
102+
del count[char]
103+
104+
for char, freq in count.items():
105+
result.append(char * freq)
106+
107+
return ''.join(result)
108+
```
109+
#### Java
110+
```java
111+
class Solution {
112+
public String customSortString(String order, String s) {
113+
Map<Character, Integer> count = new HashMap<>();
114+
for (char c : s.toCharArray()) {
115+
count.put(c, count.getOrDefault(c, 0) + 1);
116+
}
117+
118+
StringBuilder result = new StringBuilder();
119+
for (char c : order.toCharArray()) {
120+
if (count.containsKey(c)) {
121+
int freq = count.get(c);
122+
for (int i = 0; i < freq; i++) {
123+
result.append(c);
124+
}
125+
count.remove(c);
126+
}
127+
}
128+
129+
for (Map.Entry<Character, Integer> entry : count.entrySet()) {
130+
char c = entry.getKey();
131+
int freq = entry.getValue();
132+
for (int i = 0; i < freq; i++) {
133+
result.append(c);
134+
}
135+
}
136+
137+
return result.toString();
138+
}
139+
}
140+
```
141+
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)