Bird
Raised Fist0

Given the following Python code snippet implementing the optimal alien dictionary solution, what is the final returned order for the input words = ["wrt", "wrf", "er", "ett", "rftt"]?

easy🧾 Code Trace Q12 of Q15
Topological Sort - Alien Dictionary (Infer Character Order)
Given the following Python code snippet implementing the optimal alien dictionary solution, what is the final returned order for the input words = ["wrt", "wrf", "er", "ett", "rftt"]?
from collections import defaultdict, deque

def alienOrder(words):
    graph = defaultdict(set)
    in_degree = {c: 0 for word in words for c in word}

    for i in range(len(words) - 1):
        w1, w2 = words[i], words[i + 1]
        min_len = min(len(w1), len(w2))
        if len(w1) > len(w2) and w1[:min_len] == w2[:min_len]:
            return ""
        for j in range(min_len):
            if w1[j] != w2[j]:
                if w2[j] not in graph[w1[j]]:
                    graph[w1[j]].add(w2[j])
                    in_degree[w2[j]] += 1
                break

    queue = deque([c for c in in_degree if in_degree[c] == 0])
    order = []
    while queue:
        c = queue.popleft()
        order.append(c)
        for nei in graph[c]:
            in_degree[nei] -= 1
            if in_degree[nei] == 0:
                queue.append(nei)
    if len(order) < len(in_degree):
        return ""
    return "".join(order)

print(alienOrder(words))
A"wretf"
B"wertf"
C"wert"
D"wrtef"
Step-by-Step Solution
Solution:
  1. Step 1: Build graph and in-degree map

    Edges: w->e, e->r, r->t, t->f. In-degree counts: w=0, e=1, r=1, t=1, f=1.
  2. Step 2: Perform BFS topological sort

    Start with 'w' (in-degree 0), then 'e', 'r', 't', 'f' in order as their in-degree drops to zero.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Order "wertf" respects all precedence edges [OK]
Quick Trick: Trace BFS queue and in-degree updates [OK]
Common Mistakes:
MISTAKES
  • Stopping early and missing characters
  • Misordering characters with same in-degree
  • Ignoring prefix invalid case
Trap Explanation:
PITFALL
  • Off-by-one errors in loop or incorrect in-degree updates cause wrong order or missing chars.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute BFS topological sort and track in-degree changes.
Master "Alien Dictionary (Infer Character Order)" in Topological Sort

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Topological Sort Quizzes