Bird
Raised Fist0
Interview Preptopological-sortmediumAmazonGoogle

Sequence Reconstruction (Unique Topo Order)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize graph and nodes set

We start by extracting all unique nodes from the sequences and initializing an empty graph with no edges yet.

💡 Identifying all nodes upfront ensures we know the full set of elements to process and can detect missing elements early.
Line:graph = defaultdict(set) nodes = set() for seq in seqs: for num in seq: nodes.add(num)
💡 The nodes set contains {1, 2, 3}, matching the original sequence elements.
📊
Sequence Reconstruction (Unique Topo Order) - Watch the Algorithm Execute, Step by Step
Watching each step of the DFS traversal and how the algorithm detects cycles and uniqueness helps you understand the subtle conditions that make a topological order unique or ambiguous.
Step 1/11
·Active fill★Answer cell
Visiting: none
1
2
3
Visiting: none
1
2
3
Visiting: none
1
2
3
Visiting: 1
1
2
3
Visiting: 2
Edge: 1 → 2
1
2
3
Visiting: 1
1
2
3
Queue / Stack
2
Visiting: 3
Edge: 1 → 3
1
2
3
Queue / Stack
2
Visiting: 1
1
2
3
Queue / Stack
23
Visiting: none
1
2
3
Queue / Stack
231
Visiting: none
1
2
3
Queue / Stack
132
Visiting: none
1
2
3
Queue / Stack
132

Key Takeaways

✓ DFS postorder traversal produces a valid topological order by finishing nodes after all descendants.

This is hard to see from code alone because the recursion stack and node states are implicit; visualization shows the exact order nodes finish.

✓ Multiple valid topological orders can exist if the graph has branching edges, causing reconstruction to be non-unique.

Seeing the candidate order differ from the original sequence reveals why uniqueness fails, which is subtle without visualizing the stack reversal.

✓ Cycle detection via node states (processing vs done) prevents infinite recursion and invalid orders.

Understanding how marking nodes as processing helps detect cycles is clearer when watching node state changes step-by-step.

Practice

(1/5)
1. You are given an undirected tree with n nodes. The task is to find all nodes that, when chosen as roots, produce trees with minimum height. Which algorithmic approach best guarantees an optimal solution for this problem?
easy
A. Iteratively remove leaf nodes layer by layer until 1 or 2 centroids remain.
B. Use dynamic programming to store subtree heights and combine results.
C. Run BFS/DFS from every node to calculate tree height and pick minimum roots.
D. Apply a greedy approach by always choosing the node with maximum degree as root.

Solution

  1. Step 1: Understand the problem structure

    The problem asks for nodes that minimize tree height when chosen as roots. This corresponds to finding centroids of the tree.
  2. Step 2: Identify the correct approach

    Iteratively trimming leaves (nodes with degree 1) layer by layer reduces the tree towards its centroids. This approach guarantees finding the minimum height roots efficiently.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Leaf trimming is the known optimal pattern for Minimum Height Trees [OK]
Hint: Leaf trimming finds centroids efficiently [OK]
Common Mistakes:
  • Thinking BFS from each node is efficient
  • Confusing DP with leaf trimming
  • Greedy max-degree node is incorrect
2. Consider the following Python code implementing the optimal leaf trimming approach for Minimum Height Trees. Given n = 4 and edges = [[1,0],[1,2],[1,3]], what is the final returned list?
easy
A. [3]
B. [0, 2, 3]
C. [2]
D. [1]

Solution

  1. Step 1: Initialize graph and degrees

    Nodes: 0,1,2,3; edges connect 1 to 0,2,3. Degrees: 0->1, 1->3, 2->1, 3->1. Leaves initially: [0,2,3].
  2. Step 2: Trim leaves until ≤ 2 nodes remain

    Remove leaves [0,2,3], decrement neighbors' degrees. Node 1 degree reduces from 3 to 0, becomes leaf. Remaining nodes = 4 - 3 = 1. Loop ends. Return [1].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Only node 1 remains as centroid after trimming [OK]
Hint: Leaves trimmed until ≤2 nodes remain [OK]
Common Mistakes:
  • Returning initial leaves
  • Off-by-one in loop
  • Not updating degrees correctly
3. Consider the following buggy code snippet for topological sort positions. Which line contains the subtle bug that can cause incorrect matrix construction?
medium
A. Line where graph[u].append(v) is called
B. Line where queue is initialized with nodes of zero in-degree
C. Line where pos[node] is assigned idx
D. Line where in_degree[u] is incremented instead of in_degree[v]

Solution

  1. Step 1: Identify how in-degree is updated

    In-degree should count incoming edges; incrementing in_degree[u] is incorrect because u is the source, not the target.
  2. Step 2: Understand impact of bug

    Incorrect in-degree counts cause wrong zero in-degree nodes, breaking topological order and matrix correctness.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct in-degree update is critical for cycle detection and ordering [OK]
Hint: In-degree counts incoming edges, not outgoing [OK]
Common Mistakes:
  • Mixing source and target when updating in-degree
  • Assuming graph edges are undirected
4. What is the time complexity of the optimal algorithm that uses topological sort combined with iterative DP to find the largest color value in a directed graph with n nodes and e edges?
medium
A. O(n * 26 * e) due to nested loops over edges and colors
B. O(n^2) since DP updates require comparing all pairs of nodes
C. O(n + e) ignoring the 26 colors dimension as constant
D. O((n + e) * 26) because each node and edge is processed once with 26 color updates

Solution

  1. Step 1: Identify main loops

    Topological sort processes each node and edge once, so base complexity is O(n + e).
  2. Step 2: Account for DP color dimension

    For each node and edge, 26 colors are updated, multiplying complexity by 26.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Complexity is O((n + e) * 26), which is linear in graph size with constant color factor [OK]
Hint: Remember DP color dimension multiplies base graph traversal [OK]
Common Mistakes:
  • Ignoring 26 colors or assuming quadratic complexity
5. What is the time complexity of the optimal BFS-based topological sort algorithm for the Parallel Courses problem, given n courses and m prerequisite relations?
medium
A. O(n + m) because each node and edge is processed once in BFS
B. O(m^2) because updating indegrees requires scanning all edges repeatedly
C. O(n * m) because for each course you process all edges
D. O(n^2) because in the worst case all courses depend on all others

Solution

  1. Step 1: Analyze graph traversal

    Each course (node) is enqueued and dequeued at most once; each edge is visited once when decrementing indegree.
  2. Step 2: Combine node and edge processing

    Total operations proportional to number of nodes plus edges -> O(n + m).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Linear time in nodes and edges [OK]
Hint: Each edge and node processed once in BFS [OK]
Common Mistakes:
  • Assuming nested loops cause O(n*m)
  • Confusing indegree updates as repeated scans
  • Assuming dense graph means O(n^2) always
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