Bird
Raised Fist0

In the following alien dictionary code snippet, which line is most likely to cause incorrect in-degree calculation leading to wrong character order?

medium🐛 Buggy Code Q7 of Q15
Topological Sort - Alien Dictionary (Infer Character Order)
In the following alien dictionary code snippet, which line is most likely to cause incorrect in-degree calculation leading to wrong character order?
for i in range(len(words) - 1):
    word1, word2 = words[i], words[i+1]
    for c1, c2 in zip(word1, word2):
        if c1 != c2:
            graph[c1].append(c2)
            indegree[c2] += 1
            break
    else:
        if len(word1) > len(word2):
            return ""  # invalid input
ALine adding edge to graph
BBreak statement after first differing character
CLine incrementing indegree[c2]
DPrefix length check returning empty string
Step-by-Step Solution
Solution:
  1. Step 1: Understand indegree update

    Indegree must be incremented exactly once per unique edge.
  2. Step 2: Identify subtle bug

    If indegree[c2] is incremented multiple times due to repeated edges, counts become incorrect.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Indegree must reflect unique incoming edges only [OK]
Quick Trick: Indegree increments must match unique edges only [OK]
Common Mistakes:
MISTAKES
  • Blaming break statement which correctly stops after first difference
  • Thinking prefix length check causes indegree errors
  • Ignoring multiple edges causing overcounting
Trap Explanation:
PITFALL
  • Indegree increment looks correct but may double count edges
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle bugs in graph construction
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