Sort words by a custom alphabet
I was asked this
No reports yet. Sign in to say where you were asked it.
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
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"]
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
orderlowercase 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.translateto 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
chas one letter.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
