← Questions

Sort words by a custom alphabet

0
AmazonCoding

A coding interview question asked at Amazon. It tests sorting, strings and hash map.

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"]

Clarifying questions

  • If a word has a character that is not in order, should it raise an error, sort after every known character, or be dropped?
  • Is the sort required to be stable, so equal words keep their order?
  • Are the words all lowercase, and is order lowercase too?

What a strong answer covers

  • Builds a map from each character to its rank in order, then sorts with a key that turns each word into a list or tuple of ranks. Tuples compare left to right and a shorter prefix comes first, which is exactly the rule.
  • O(total characters) to build the keys and O(n log n) comparisons, each up to 100 characters long.
  • Can use str.translate to map each word to a string that sorts the same way, which is faster than building tuples.
  • Edge cases: an empty list, empty words, duplicates, and a word that is a prefix of another.
  • Tests: both examples, a reversed alphabet, duplicate words, and a word with an unknown character handled as agreed.

Follow-ups

  • Check whether a list is already sorted under the alphabet, in one pass.
  • Given a list sorted under an unknown alphabet, find the alphabet (a topological sort).
  • The alphabet changes between calls: avoid re-sorting from scratch.
  • Compare multi-character letters, such as ch as one letter.

Where it's asked

What it tests

sorting · strings · hash map

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