You get a list of lowercase words, words. A word is buildable if you can reach it by starting from a one-letter word in the list and adding one letter at a time to the end, where every word along the way is also in the list.
Return the longest buildable word. If several share that length, return the one that comes first in alphabetical order. If no word is buildable, return the empty string.
Example 1
Input: words = ["t", "to", "tip", "ti", "top"] Output: "tip" Why: tip and top are both buildable; tip is first alphabetically
2 more examples and the constraints
Example 2
Input: words = ["k", "ki", "kit", "kits", "kite", "z"] Output: "kite" Why: k, ki, kit, then kite or kits; kite is first alphabetically
Example 3
Input: words = ["ab", "abc"] Output: "" Why: there is no one-letter word to start from
Constraints
- 1 ≤ length of words ≤ 1,000
- 1 ≤ length of each word ≤ 30
- Words use only the letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every prefix in a setO(Σ L²)
- Trie + depth-first searchO(Σ L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 words of 30 letters | Verdict |
|---|---|---|---|
| Check every prefix in a set | O(Σ L²) | Passes; rebuilds prefixes | |
| Trie + depth-first search | O(Σ L) | Best; each prefix once |
L = length of a word, Σ L = total letters in all the words.
Edge cases to test
- No one-letter word. ["ab", "abc"] gives "": nothing can start a chain.
- A gap in the chain. ["a", "ab", "abcd"] gives "ab": abcd needs abc.
- Ties on length. ["b", "a", "ba", "ab"] gives "ab", the alphabetically smaller one.
- Repeated words. ["a", "a", "ab"] gives "ab"; duplicates change nothing.
- A single letter. ["q"] gives "q": a one-letter word is buildable by itself.
Common mistakes
- Only checking the prefix one letter shorter, without making sure that prefix is itself buildable.
- Replacing
beston a tie, which keeps the alphabetically larger word. - Walking into a trie node that does not end a word, which lets gaps through.
How to talk through it
- 1Clarify. Must every step be a word in the list? How are ties broken? What if nothing works?
- 2Give the set approach. A word is buildable when all its prefixes are words. Check them in a set.
- 3Spot the shared prefixes. Words share their starts, so a trie stores each prefix once.
- 4Code the search. Only step into nodes that end a word; visit a to z; replace only when longer.
- 5Test out loud. Run the tie, the gap and the no-one-letter cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?