DSA With AI
Week 6 ยท Graphs

Alien Dictionary

Solve Alien Dictionary by recognizing the Graphs pattern and turning the prompt into a small invariant before coding.

Hard Graphs Week 6 Practice runner

Frame the problem

  • Implement alien_order with the exact signature used by the interactive runner.
  • Use the visible tests to confirm the input and output shape before reading the final solution.
  • Treat challenge tests as edge-case pressure: empty inputs, repeated values, boundary shapes, or impossible states.
  • State the invariant before code, then dry-run one passing case and one failing-looking case.
1. Reveal example inputs and outputs

Example 1

Input:

alien_order([
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
])

Output:

"wertf"
2. Brute force first

What direct brute force would be correct for a tiny input? Name the exact repeated work that the target pattern removes.

3. Reveal the insight ladder
  1. Map the prompt to the Graphs pattern instead of starting from syntax.
  2. The first differing character between adjacent words creates one directed edge.
  3. A longer word cannot appear before its exact prefix in a valid lexicographic ordering.
  4. Only reveal the final code after you can explain why each state update is safe.
4. Dry run before code
  1. alien-dictionary-basic: input [["wrt","wrf","er","ett","rftt"]] should produce "wertf". Hint to check your state: The first differing character between adjacent words creates one directed edge.
  2. alien-dictionary-invalid-prefix: input [["abc","ab"]] should produce "". Hint to check your state: A longer word cannot appear before its exact prefix in a valid lexicographic ordering.
5. Reveal final Python solution
def alien_order(words: list[str]) -> str:
    graph = {char: set() for word in words for char in word}
    indegree = {char: 0 for char in graph}
    for first, second in zip(words, words[1:]):
        if len(first) > len(second) and first.startswith(second):
            return ""
        for a, b in zip(first, second):
            if a != b:
                if b not in graph[a]:
                    graph[a].add(b)
                    indegree[b] += 1
                break

    queue = deque(sorted(char for char, degree in indegree.items() if degree == 0))
    order = []
    while queue:
        char = queue.popleft()
        order.append(char)
        for nxt in sorted(graph[char]):
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return "".join(order) if len(order) == len(graph) else ""

Complexity: Derive the exact bounds from alien_order: count how often each input item is visited and the maximum size of the main state structure.

Interview narration

  • I will first describe the invariant in plain language.
  • Then I will explain what data structure carries that invariant across the traversal, loop, recursion, or DP transition.
  • Finally I will walk one edge case before writing the optimized version.

Common traps

  • Solving only the visible example instead of the invariant.
  • Forgetting empty input, singleton input, duplicate values, or impossible-state cases.
  • Revealing the solution before doing a dry run from the starter signature.

Follow-up drills

1. How do you turn this into a timed interview answer?

Start with the invariant, give the brute force in one sentence, name the optimized state, code the core loop or recursion, and run one visible test aloud before mentioning complexity.

2. How do you scale the same pattern to a larger input?

Track which state grows with the input: hash maps and sets grow with distinct values, queues grow with frontier width, recursion grows with depth, heaps grow with active candidates, and DP tables grow with state count.

3. What should you practice from blank tomorrow?

Rewrite alien_order without looking at the solution, then compare only the invariant and state updates before checking syntax.

Interactive runner

Write the required Python function. Your code runs locally in this browser. Hints reveal one failing case at a time.