Shortest unique prefix for each word
I was asked this
No reports yet. Sign in to say where you were asked it.
Given a list of distinct words, return for each word its shortest unique prefix: the shortest leading substring of the word that no other word in the list starts with. Return the answers in the same order as the input.
def shortest_unique_prefixes(words: list[str]) -> list[str]: ...
Constraints
- 1 ≤
len(words)≤ 10⁵ - 1 ≤
len(words[i])≤ 100 - Words contain only lowercase letters
a–z. - No word is a prefix of another word, so every word has a unique prefix.
Example 1
Input: ["kiwi", "kale", "kelp", "fig"]
Output: ["ki", "ka", "ke", "f"]
All three k words share k, but their second letters differ. fig is the only word starting with f.
Example 2
Input: ["tram", "trap", "tree", "zoo"]
Output: ["tram", "trap", "tre", "z"]
tram and trap first differ at the fourth letter, so each needs the whole word.
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.
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 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.
