Bird
Raised Fist0
Interview Preptopological-sorthardAmazonGoogle

Build a Matrix With Conditions

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Row Graph and In-Degree

Create adjacency list and in-degree array for row conditions. For each condition [u,v], add edge u->v and increment in-degree of v.

💡 Building the graph and in-degree array sets up the dependency structure needed for topological sorting.
Line:graph = [[] for _ in range(n + 1)] in_degree = [0] * (n + 1) for u, v in conditions: graph[u].append(v) in_degree[v] += 1
💡 The graph and in-degree arrays represent all row dependencies explicitly.
📊
Build a Matrix With Conditions - Watch the Algorithm Execute, Step by Step
Watching each step of the topological sort and matrix construction reveals how dependencies translate into positions, making the abstract concept concrete and intuitive.
Step 1/16
·Active fill★Answer cell
Visiting: none
1
2
3
Visiting: none
1
2
3
Queue / Stack
1
Visiting: 1
1
2
3
Visiting: 1
Edge: 1 → 2
1
2
3
Queue / Stack
2
Visiting: 2
1
2
3
Visiting: 2
Edge: 2 → 3
1
2
3
Queue / Stack
3
Visiting: 3
1
2
3
Visiting: none
1
2
3
Visiting: none
1
2
3
Queue / Stack
3
Visiting: 3
1
2
3
Visiting: 3
Edge: 3 → 2
1
2
3
Queue / Stack
2
Visiting: 2
1
2
3
Visiting: 2
Edge: 2 → 1
1
2
3
Queue / Stack
1
Visiting: 1
1
2
3
Visiting: none
1
2
3
Visiting: none
1
2
3

Key Takeaways

✓ Topological sorting assigns positions respecting all dependency constraints.

Seeing nodes move from queue to done with position assignment clarifies how order is established beyond code.

✓ Separate topological sorts for rows and columns handle independent constraints elegantly.

Visualizing two graphs and their sorts side-by-side reveals how row and column orders combine to position elements.

✓ Cycle detection via incomplete processing ensures invalid inputs return empty results.

Watching the queue empty prematurely or nodes unprocessed highlights when no valid order exists.

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. What is the time complexity of Kahn's Algorithm for finding a topological order in a graph with V vertices and E edges?
medium
A. O(V * E) because each vertex processes all edges repeatedly.
B. O(V^2) because in-degree updates require scanning all vertices.
C. O(V + E) because each vertex and edge is processed exactly once.
D. O(E log V) due to priority queue operations for ordering.

Solution

  1. Step 1: Identify operations on vertices and edges

    Each vertex is enqueued and dequeued once; each edge is visited once to decrement in-degree.
  2. Step 2: Sum total work

    Processing all vertices and edges once leads to O(V + E) time complexity.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Linear time in graph size is standard for BFS topological sort [OK]
Hint: Each edge and vertex processed once -> O(V + E) [OK]
Common Mistakes:
  • Assuming nested loops cause O(V*E)
  • Confusing in-degree updates as scanning all vertices
  • Thinking priority queues are used by default
3. What is the time complexity of the optimal leaf trimming algorithm for finding Minimum Height Trees in a tree with n nodes and n-1 edges?
medium
A. O(n²) because each leaf removal requires scanning all nodes.
B. O(n) because each edge and node is processed at most once during trimming.
C. O(n log n) due to priority queue operations for leaf selection.
D. O(n + m) where m is the number of edges, which equals n-1 here.

Solution

  1. Step 1: Analyze leaf trimming operations

    Each node is added and removed from the leaves queue at most once. Each edge is visited when decrementing degrees.
  2. Step 2: Combine node and edge processing

    Since the graph is a tree, edges = n-1. Total operations proportional to n.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Linear time complexity matches leaf trimming algorithm [OK]
Hint: Each node and edge processed once [OK]
Common Mistakes:
  • Assuming O(n²) due to nested loops
  • Confusing with BFS from each node
  • Thinking priority queue is used
4. Suppose the course prerequisites can form multiple disconnected subgraphs and some courses have no prerequisites. How should Kahn's Algorithm be modified to return a valid order including all courses?
hard
A. Initialize the queue with all nodes having zero in-degree, including those in disconnected components.
B. Use backtracking to try all permutations since BFS cannot handle disconnected graphs.
C. Run DFS from each node separately and concatenate results without cycle checks.
D. Start BFS from any arbitrary node and ignore disconnected components.

Solution

  1. Step 1: Identify disconnected components

    Courses with no prerequisites form disconnected subgraphs with zero in-degree nodes.
  2. Step 2: Initialize queue with all zero in-degree nodes

    Queue must include all such nodes to process all components and produce a full valid order.
  3. Step 3: Process BFS as usual

    Processing all zero in-degree nodes ensures all courses are included in the order.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Queue initialization with all zero in-degree nodes covers disconnected graphs [OK]
Hint: Queue must start with all zero in-degree nodes, not just one [OK]
Common Mistakes:
  • Starting BFS from a single node only
  • Ignoring disconnected components
  • Skipping cycle detection in DFS
5. Suppose the problem is modified so that elements in the sequences can be reused multiple times (i.e., sequences may contain repeated elements). Which of the following changes to the DFS postorder topological sort approach is necessary to correctly determine if the original sequence can be uniquely reconstructed?
hard
A. No changes needed; the existing DFS approach handles repeated elements naturally.
B. Modify graph construction to allow multiple edges between the same nodes and adjust cycle detection accordingly.
C. Switch to BFS topological sort with a queue that tracks in-degree counts considering repeated edges.
D. Preprocess sequences to remove duplicates before building the graph, then run the original DFS approach.

Solution

  1. Step 1: Understand impact of repeated elements

    Repeated elements mean multiple edges between same nodes may exist, affecting graph structure and cycle detection.
  2. Step 2: Adjust graph and DFS accordingly

    Graph must allow multiple edges or count edge multiplicity; cycle detection must consider these to avoid false negatives or infinite recursion.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Handling repeated edges is essential for correctness with reused elements [OK]
Hint: Repeated elements require multi-edge aware graph and cycle detection [OK]
Common Mistakes:
  • Assuming no changes needed
  • Removing duplicates loses info
  • Switching to BFS without handling repeats
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