Read the alphabet off a sorted list
words is a list of lowercase words, sorted by the rules of an alphabet whose order of letters you do not know. Two neighbouring words, compared at the first place where they differ, tell you which of those two letters comes first. Nothing else in the list says anything about the order.
Return every letter that appears in words, each once, in an order that agrees with everything the list tells you. When more than one order agrees, return the one that comes first in ordinary a to z order.
If no order agrees, return an empty string. That happens when the rules contradict each other, or when a word comes before a shorter word that is its own beginning, such as "abc" before "ab".
- Input
words = ["mz","mk","zq","za","qa","qk"]- Output
"mzqak"
The neighbours say z before k, m before z, q before a, z before q and a before k. Only m, z, q, a, k fits all five.
- Input
words = ["za","zb","yx"]- Output
"abxzy"
The list says a before b and z before y, and nothing else. Of all the orders that fit, abxzy comes first from a to z.
- Input
words = ["abc","ab"]- Output
""
"ab" is the beginning of "abc", so it would come first in any alphabet.
Limits
1 <= words.length <= 10001 <= words[i].length <= 20words[i] holds lowercase English letters
Hints
Hint 1
Only the first differing letter of each pair of neighbours gives a rule. Each rule is an edge in a graph of letters.
Hint 2
Take letters with no rule against them, smallest first: keep the ready ones in a min-heap. If some letters never become ready, the rules have a cycle.
Where this was reported
- Intuit, SWE intern campus interview, 2026 (LeetCode)
- Amazon, SDE-1 interview, 2026 (Medium)
Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.
Run your code to check it on the examples. Submit runs every hidden test.

