Letters of a Made-Up Language
Medium · Topological Sort & Shortest Paths · about 25 min
A game uses a made-up language written with lowercase English letters, but its alphabet is in a different order. You get words, a list of words that is already sorted in the made-up order, using the usual dictionary rules: compare the first letter where two words differ, and a word comes before any longer word that starts with it.
Return a string with every distinct letter that appears in words, in an order that agrees with the list. Whenever several letters could come next, put the one that is earliest in the English alphabet first, so the answer is unique. If no alphabet can make the list sorted, return "".
1 <= len(words) <= 1000, every word has 1 to 50 letters.
Example: made_up_alphabet(["wrt", "wrf", "er", "ett", "rftt"]) → "wertf"
Example: made_up_alphabet(["abc", "ab"]) → "" (a word can't come before its own prefix).
Hints
- Compare only words that sit next to each other. Which single letter pair does each comparison reveal?
- Stop at the first position where the two words differ. If there is none and the first word is longer, the list is broken.
- The rules are arrows between letters. Kahn's algorithm with 'smallest free letter first' gives the unique answer; a loop means fewer letters come out.
Learn the pattern first: the Topological Sort & Shortest Paths lesson.
More Topological Sort & Shortest Paths problems
- Finish Every Training Module (Easy)
- Alarm Across the Campus (Easy)
- Does One Skill Lead to Another? (Easy)
- Flip the Fewest One-Way Signs (Easy)
- Fewest Terms to Graduate (Medium)
- Budget Trip With Few Layovers (Medium)
- The Gentlest Hike (Medium)
- Wire Up the Sensors (Medium)
- Pick the Quietest Depot (Medium)
- Rebuild the Travel Route (Medium)
- Cross Before the Flood (Hard)
- How Many Fastest Routes? (Hard)
- Earliest Launch Day (Hard)
- Toll Roads With Coupons (Hard)