MediumNo. 0791
Custom Sort String — LeetCode 791 Python Solution
- Pattern
- Sorting
- Topics
- Hash Table, String, Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Python solution
class Solution:
def customSortString(self, order: str, s: str) -> str:
d = {c: i for i, c in enumerate(order)}
return ''.join(sorted(s, key=lambda x: d.get(x, 0)))Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 791. Custom Sort String is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0792 | Number of Matching Subsequences | Medium |
| 0049 | Group Anagrams | Medium |
| 0242 | Valid Anagram | Easy |
| 0389 | Find the Difference | Easy |
| 0451 | Sort Characters By Frequency | Medium |
| 0522 | Longest Uncommon Subsequence II | Medium |
Frequently asked questions
- How hard is LeetCode 791. Custom Sort String?
LeetCode 791. Custom Sort String is rated Medium on LeetCode.
- What is the time complexity of LeetCode 791. Custom Sort String?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 791. Custom Sort String?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 791. Custom Sort String cover?
LeetCode 791. Custom Sort String is tagged Hash Table, String and Sorting on LeetCode.