Custom Sort String — LeetCode 791 Python Solution

MediumHash TableStringSorting
Problem
#791
Pattern
Sorting
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview