Recover a Letter Ordering from a Sorted Word List
Trees & GraphsAuto-graded · 27 test casesLast updated
Derive precedence constraints between letters from adjacent sorted words, then topologically sort them while detecting contradictions and invalid prefix orderings.
Recover a Letter Ordering from a Sorted Word List
A made-up language uses lowercase English letters, but its alphabet order is unknown. You are given a list of non-empty words that a dictionary of this language lists in sorted order, using ordinary lexicographic comparison under the unknown alphabet.
Decide whether some alphabet order could make the list correctly sorted. If one exists, return a string containing every distinct letter that appears in the words, arranged in an order that works. If none exists, return the empty string "".
Rules
- Two words are compared left to right. The first position where they differ decides which word comes first.
- If one word is a proper prefix of the other, the shorter word must come first. A list where a longer word comes directly before its own proper prefix (for example
["abc", "ab"]) cannot be valid. - Identical neighbouring words are fine and give no information.
- Letters that have no constraints relating them to others must still appear in the output.
- If more than one ordering is valid, returning any one of them is acceptable.
- If the constraints contradict each other (for example,
amust precedebandbmust precedea), return"".
Input
words: a list of strings.
Output
- A string with each distinct letter from
wordsexactly once, in a valid alphabet order, or""if no valid order exists.
Constraints
1 <= len(words) <= 1001 <= len(words[i]) <= 100- Each word consists of lowercase English letters only.
Examples
Example 1
Input: derive_letter_order(['wrt', 'wrf', 'er', 'ett', 'rftt'])
Output: 'wertf'
Example 2
Input: derive_letter_order(['z', 'x', 'z'])
Output: ''
Example 3
Input: derive_letter_order(['abc', 'ab'])
Output: ''
Hints
Hint 1
Only neighbouring words need to be compared. For each adjacent pair, the first position where they differ gives exactly one 'this letter comes before that letter' fact, and nothing after that position matters.
Hint 2
Treat each letter as a node and each fact as a directed edge. A valid alphabet is a topological order of this graph, and a cycle means the list is impossible.
Hint 3
Do not forget two traps: a longer word followed by its own prefix produces no differing character and must be rejected explicitly, and repeated identical edges must not be counted twice in the in-degree.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Lexicographic order is decided by the first position where two words differ, so every adjacent pair of words yields at most one fact of the form "letter a comes before letter b". Non-adjacent pairs add nothing new, because the ordering is transitive.
- Register every distinct letter as a node with in-degree 0, so unconstrained letters still appear in the answer.
- For each adjacent pair, find the first differing position. If there is one, add the edge
a -> b, skipping it if that edge was already added so in-degrees are not inflated. - If there is no differing position and the earlier word is longer, it is a longer word before its own prefix. Return
"". - Run Kahn's algorithm: repeatedly output a letter with in-degree 0 and decrement the in-degrees of its successors.
- If fewer letters were output than exist, a cycle blocked the sort. Return
"".
Why it is correct
- Each extracted edge is a necessary condition for the list to be sorted, so any valid alphabet must respect all of them.
- Any topological order of the graph satisfies every edge, so every adjacent pair is correctly ordered. By transitivity the whole list is sorted.
- Letters on a cycle never reach in-degree 0, so the output is too short exactly when the constraints contradict each other.
- The prefix violation creates no edge, so it has to be checked separately.
Complexity
Let C be the total number of characters, U <= 26 the number of distinct letters and E the number of distinct edges.
- Time:
O(C + U + E). - Space:
O(U + E), which is bounded by a constant for a 26-letter alphabet.
Reference solution
from typing import List
from collections import deque
def derive_letter_order(words: List[str]) -> str:
# Every letter that appears is a node; dict keeps first-appearance order.
in_degree = {}
for word in words:
for ch in word:
if ch not in in_degree:
in_degree[ch] = 0
adj = {ch: [] for ch in in_degree}
seen_edges = set()
for i in range(len(words) - 1):
first, second = words[i], words[i + 1]
shared = min(len(first), len(second))
# A longer word cannot precede its own prefix.
if len(first) > len(second) and first[:shared] == second[:shared]:
return ""
for j in range(shared):
if first[j] != second[j]:
edge = (first[j], second[j])
if edge not in seen_edges:
seen_edges.add(edge)
adj[first[j]].append(second[j])
in_degree[second[j]] += 1
break
queue = deque(ch for ch in in_degree if in_degree[ch] == 0)
order = []
while queue:
cur = queue.popleft()
order.append(cur)
for nxt in adj[cur]:
in_degree[nxt] -= 1
if in_degree[nxt] == 0:
queue.append(nxt)
if len(order) != len(in_degree):
return ""
return "".join(order)