← Questions

Sort words by a custom alphabet

0
AmazonCoding

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 order comes 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 in order (ask your interviewer what to do if one does not).
  • 0 <= len(words) <= 10^5, and 0 <= 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.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding