Sort words by a custom alphabet
I was asked this
No reports yet. Sign in to say where you were asked it.
You are given a string order that lists characters from first to last in a custom alphabet. Each character appears in order at most once. You are also given a list of strings words.
Return words sorted by dictionary order under this alphabet:
- Compare two words from left to right. At the first position where they differ, the word whose character appears earlier in
ordercomes first. - If one word is a prefix of the other, the shorter word comes first.
- Equal words are both kept in the output.
Implement:
def custom_sort(order: str, words: list[str]) -> list[str]: ...
Constraints
-
1 <= len(order) <= 26, and every character in every word appears inorder(ask your interviewer what to do if one does not). -
0 <= len(words) <= 10^5, and0 <= len(word) <= 100.
Example 1
order = "cba"
words = ["ab", "a", "c", "ba"]
output: ["c", "ba", "a", "ab"]
c ranks before b, which ranks before a. "a" is a prefix of "ab", so it comes first.
Example 2
order = "zyxwvutsrqponmlkjihgfedcba"
words = ["apple", "zoo", "banana"]
output: ["zoo", "banana", "apple"]
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
