Bird
Raised Fist0
Interview Preptopological-sorthardAmazonGoogle

Longest Path With Different Adjacent Characters

Choose your preparation mode4 modes available
▶
Steps
setup

Build graph and compute in-degree

We initialize the graph adjacency list and in-degree array. For each edge, we add the destination node to the source's adjacency list and increment the destination's in-degree.

💡 This step sets up the graph structure and in-degree counts needed for topological sorting.
Line:graph = defaultdict(list) indegree = [0] * n for u, v in edges: graph[u].append(v) indegree[v] += 1
💡 The graph and in-degree arrays represent the problem dependencies and readiness for processing.
📊
Longest Path With Different Adjacent Characters - Watch the Algorithm Execute, Step by Step
Watching each step reveals how topological sorting and DP combine to solve a complex graph problem efficiently, making the abstract code concrete and understandable.
Step 1/19
·Active fill★Answer cell
Visiting: none
0
1
2
3
4
Visiting: none
0
1
2
3
4
Queue / Stack
0
Visiting: 0
0
1
2
3
4
Visiting: 0
Edge: 0 → 1
0
1
2
3
4
Queue / Stack
1
Visiting: 1
0
1
2
3
4
Visiting: 1
Edge: 1 → 2
0
1
2
3
4
Queue / Stack
2
Visiting: 2
0
1
2
3
4
Visiting: 2
Edge: 2 → 3
0
1
2
3
4
Queue / Stack
3
Visiting: 3
0
1
2
3
4
Visiting: 3
Edge: 3 → 4
0
1
2
3
4
Queue / Stack
4
Visiting: 4
0
1
2
3
4
Visiting: none
0
1
2
3
4
Visiting: none
0
1
2
3
4
Visiting: 0
Edge: 0 → 1
0
1
2
3
4
Visiting: 1
Edge: 1 → 2
0
1
2
3
4
Visiting: 2
Edge: 2 → 3
0
1
2
3
4
Visiting: 3
Edge: 3 → 4
0
1
2
3
4
Visiting: none
0
1
2
3
4
Visiting: none
0
1
2
3
4

Key Takeaways

✓ Topological sorting orders nodes so dependencies are processed before dependents.

This ordering is essential for correctly propagating longest path values without revisiting nodes.

✓ Dynamic programming updates longest path lengths only when adjacent characters differ.

This condition enforces the problem constraint and shows how DP can incorporate problem-specific rules.

✓ Cycle detection via topological sort length check prevents invalid computations.

Without this check, the algorithm could run infinitely or produce incorrect results on cyclic graphs.

Practice

(1/5)
1. 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))
easy
A. "wretf"
B. "wertf"
C. "wert"
D. "wrtef"

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]
Hint: Trace BFS queue and in-degree updates [OK]
Common Mistakes:
  • Stopping early and missing characters
  • Misordering characters with same in-degree
  • Ignoring prefix invalid case
2. Consider the following buggy implementation of Kahn's Algorithm for course scheduling. Which line contains the subtle bug that can cause incorrect or infinite behavior?
medium
A. Line 6: graph[a].append(b) -- edge direction reversed
B. Line 7: in_degree[a] += 1 -- incorrect in-degree increment
C. Line 10: queue initialization -- wrong nodes enqueued
D. Line 15: in_degree[nei] -= 1 -- decrementing in-degree incorrectly

Solution

  1. Step 1: Analyze edge construction

    Prerequisite pairs are (a, b) meaning b -> a edge; reversing to graph[a].append(b) flips direction.
  2. Step 2: Consequences of reversed edges

    In-degree counts and BFS queue become invalid, causing wrong order or infinite loop.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct edge direction is critical for topological sort correctness [OK]
Hint: Check edge direction carefully when building graph [OK]
Common Mistakes:
  • Reversing edges when building adjacency list
  • Incrementing in-degree on wrong node
  • Forgetting to decrement in-degree
3. What is the time complexity of the optimal DFS postorder topological sort approach for sequence reconstruction, given n as the length of the original sequence and m as the total length of all sequences in seqs?
medium
A. O(n + m)
B. O(n! * m)
C. O(n * m)
D. O(m^2)

Solution

  1. Step 1: Identify graph construction cost

    Building graph from seqs takes O(m) time, where m is total length of all sequences.
  2. Step 2: Analyze DFS traversal cost

    DFS visits each node once and edges once, total O(n + m). No extra factorial or quadratic factors.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Linear time in nodes plus edges [OK]
Hint: DFS topo sort is O(V+E) -> O(n+m) here [OK]
Common Mistakes:
  • Confusing with brute force factorial complexity
  • Assuming quadratic due to nested loops
4. Suppose the problem is modified so that nodes can be revisited multiple times (cycles allowed). Which modification to the iterative DFS approach is necessary to correctly find all paths from source to target without infinite loops?
hard
A. Add a visited set per path to prevent revisiting nodes already in the current path
B. Remove path tracking and rely on global visited set to avoid cycles
C. Use BFS instead of DFS to guarantee shortest paths and avoid cycles
D. No modification needed; the current approach handles cycles correctly

Solution

  1. Step 1: Identify cycle problem

    Allowing revisits means cycles can cause infinite loops if not tracked per path.
  2. Step 2: Solution approach

    Maintain a visited set per path to avoid revisiting nodes already in the current path, preventing cycles.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Global visited set disallows legitimate different paths; per-path visited set is needed [OK]
Hint: Cycle detection requires per-path visited tracking, not global visited [OK]
Common Mistakes:
  • Using global visited set incorrectly
  • Assuming no cycles without checks
5. If the problem is extended so that the same element can appear multiple times in the matrix (i.e., reuse allowed), which modification to the topological sort approach is necessary to correctly build the matrix?
hard
A. No change needed; reuse does not affect topological ordering
B. Replace topological sort with a longest path algorithm to handle repeated elements
C. Track counts of each element and assign positions based on frequency, not just order
D. Modify graph to allow self-loops and update cycle detection accordingly

Solution

  1. Step 1: Understand reuse impact on matrix construction

    Allowing reuse means elements can appear multiple times, so positions must reflect frequency, not just order.
  2. Step 2: Adjust algorithm to track counts and assign positions accordingly

    Topological order alone does not handle multiple occurrences; tracking counts and assigning positions based on frequency is necessary.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Frequency tracking ensures correct placement of repeated elements [OK]
Hint: Reuse implies tracking element counts and positions [OK]
Common Mistakes:
  • Assuming reuse needs no algorithm change
  • Ignoring frequency of elements
  • Replacing topological sort unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard