Bird
Raised Fist0
Interview Preptopological-sortmediumAmazonFacebookGoogleMicrosoft

Course Schedule II (Topological Order)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize graph and in-degree array

Create an adjacency list for all courses and initialize an in-degree array with zeros for each course.

💡 This sets up the data structures needed to track prerequisites and how many courses depend on each course.
Line:graph = defaultdict(list) in_degree = [0] * numCourses
💡 We need to represent the graph and track in-degree counts before processing.
📊
Course Schedule II (Topological Order) - Watch the Algorithm Execute, Step by Step
Watching each step visually reveals how Kahn's Algorithm uses in-degree counts and a queue to find a valid course order, making the abstract concept concrete.
Step 1/18
·Active fill★Answer cell
Visiting: none
0
1
2
3
Visiting: none
0
1
2
3
Visiting: none
0
1
2
3
Queue / Stack
0
Visiting: 0
0
1
2
3
Visiting: 0
Edge: 0 → 1
0
1
2
3
Visiting: 0
Edge: 0 → 1
0
1
2
3
Queue / Stack
1
Visiting: 0
Edge: 0 → 2
0
1
2
3
Queue / Stack
1
Visiting: none
0
1
2
3
Queue / Stack
12
Visiting: 1
0
1
2
3
Queue / Stack
2
Visiting: 1
Edge: 1 → 3
0
1
2
3
Queue / Stack
2
Visiting: none
0
1
2
3
Queue / Stack
2
Visiting: 2
0
1
2
3
Visiting: 2
Edge: 2 → 3
0
1
2
3
Visiting: none
0
1
2
3
Queue / Stack
3
Visiting: 3
0
1
2
3
Visiting: 3
0
1
2
3
Visiting: none
0
1
2
3

Key Takeaways

✓ Kahn's Algorithm uses in-degree counts and a queue to iteratively find courses with no remaining prerequisites.

This insight is hard to see from code alone because the dynamic changes in in-degree and queue contents are abstract without visualization.

✓ The graph edges represent prerequisite dependencies, and decrementing in-degree simulates completing prerequisites.

Seeing edges change state and in-degree update visually clarifies how dependencies are resolved step-by-step.

✓ Courses are only added to the queue when their in-degree reaches zero, ensuring a valid order respecting all prerequisites.

The decision to enqueue or not is critical and is easier to understand when watching the queue evolve during the trace.

Practice

(1/5)
1. You are given a directed graph where each node has a color represented by a lowercase letter. The goal is to find the maximum number of occurrences of any single color along any path in the graph. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Greedy traversal selecting the most frequent color at each step
B. Dijkstra's algorithm to find shortest paths weighted by color frequency
C. Topological sort combined with iterative dynamic programming to track color counts
D. Simple DFS exploring all paths without memoization

Solution

  1. Step 1: Understand problem constraints and graph properties

    The problem requires tracking maximum color counts along paths in a directed graph, which may contain dependencies and cycles.
  2. Step 2: Identify suitable algorithm

    Topological sort linearizes nodes respecting dependencies, enabling iterative DP to accumulate color counts efficiently without redundant recomputation.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Topological sort + DP handles dependencies and cycles correctly [OK]
Hint: Topological sort enables DP on DAGs [OK]
Common Mistakes:
  • Assuming greedy or simple DFS suffices without cycle detection
2. You are given a list of sequences, each representing partial orderings of elements. Your task is to determine if there exists exactly one sequence that can be constructed which is consistent with all these partial orderings and matches a given original sequence. Which algorithmic approach best guarantees an efficient and correct solution for this problem?
easy
A. Use brute force to generate all permutations of the original sequence and check which ones are supersequences of all given sequences.
B. Apply a greedy approach by always choosing the smallest available element not yet placed, hoping to build the unique sequence.
C. Use dynamic programming to count the number of ways to interleave the sequences and verify if only one matches the original.
D. Construct a directed graph from the sequences and perform a DFS postorder topological sort with cycle detection and uniqueness verification.

Solution

  1. Step 1: Understand problem constraints

    The problem requires verifying if exactly one sequence matches all partial orderings, which is a classic unique topological order problem.
  2. Step 2: Identify suitable algorithm

    Brute force is inefficient; greedy and DP approaches do not guarantee correctness or uniqueness checks. DFS postorder topological sort with cycle detection and uniqueness verification efficiently solves the problem.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DFS topological sort with uniqueness check is standard for unique sequence reconstruction [OK]
Hint: Unique topo order requires graph + DFS with uniqueness check [OK]
Common Mistakes:
  • Assuming greedy or DP can guarantee uniqueness
  • Trying brute force despite factorial complexity
3. What is the time complexity of the optimal approach that uses the reversed graph and Kahn's algorithm to find eventual safe states in a graph with V vertices and E edges?
medium
A. O(V + E) because each edge and vertex is processed once during graph reversal and BFS
B. O(V^2) because we process each node and its neighbors repeatedly
C. O(V * E) due to nested loops over vertices and edges
D. O(E log V) because of sorting the safe nodes at the end

Solution

  1. Step 1: Analyze graph reversal and in-degree computation

    Reversing the graph and computing in-degree requires iterating over all edges once, O(E).
  2. Step 2: Analyze BFS processing

    Each node is enqueued and dequeued at most once, and each edge is considered once when decrementing in-degree, total O(V + E).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Linear time in vertices and edges matches BFS and graph reversal [OK]
Hint: Each edge and vertex processed once in BFS + reversal [OK]
Common Mistakes:
  • Assuming nested loops cause O(V*E)
  • Confusing sorting cost as dominant
  • Forgetting BFS processes each edge once
4. Suppose the alien dictionary problem is extended so that characters can appear multiple times in the same word and the order must reflect the first occurrence precedence only. Which modification to the topological sort approach correctly handles this variant without breaking correctness or efficiency?
hard
A. Modify graph construction to add edges for every differing character pair in all positions, not just first differing character
B. Use a brute force approach comparing all pairs of words and all character positions to build edges
C. Keep only the first differing character pair between adjacent words to add edges, ignoring subsequent differences
D. Ignore repeated characters and treat each character as unique node per occurrence

Solution

  1. Step 1: Understand variant requirement

    Order depends only on first differing character between adjacent words, even if characters repeat later.
  2. Step 2: Confirm correct approach

    Adding edges only for the first differing character pair preserves partial order and avoids cycles or redundant edges.
  3. Step 3: Reject incorrect modifications

    Adding edges for all differing pairs or treating repeated chars as unique nodes breaks correctness or efficiency.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    First differing character edge addition is minimal and sufficient [OK]
Hint: Only first differing character pair defines order [OK]
Common Mistakes:
  • Adding edges for all differing pairs causing cycles
  • Using brute force all pairs approach losing efficiency
  • Treating repeated chars as distinct nodes
5. Suppose the problem is modified so that nodes can be revisited multiple times along a path (cycles allowed), and you want the largest color value on any path (possibly infinite). Which of the following approaches correctly handles this variant?
hard
A. Detect cycles and return -1 immediately since infinite paths exist
B. Use the original topological sort + DP approach, ignoring cycles
C. Use DFS with memoization and cycle detection to find maximum color counts on simple paths only
D. Apply Bellman-Ford style relaxation over multiple iterations to handle cycles and update color counts

Solution

  1. Step 1: Understand impact of cycles

    Allowing cycles means paths can be infinitely long, so maximum color count can be unbounded.
  2. Step 2: Recognize correct handling

    Detecting cycles and returning -1 is necessary to indicate no finite maximum exists.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Infinite paths imply no finite max color value; cycle detection is mandatory [OK]
Hint: Cycles imply infinite max color count [OK]
Common Mistakes:
  • Trying to apply DP ignoring cycles or assuming memoized DFS suffices
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