Bird
Raised Fist0
Interview Preptopological-sorthardAmazonGoogle

Build a Matrix With Conditions

Choose your preparation mode4 modes available
</>
IDE
def buildMatrix(n: int, rowConditions: list[list[int]], colConditions: list[list[int]]) -> list[list[int]]:public int[][] buildMatrix(int n, int[][] rowConditions, int[][] colConditions)vector<vector<int>> buildMatrix(int n, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions)function buildMatrix(n, rowConditions, colConditions)
def buildMatrix(n, rowConditions, colConditions):
    # Write your solution here
    pass
class Solution {
    public int[][] buildMatrix(int n, int[][] rowConditions, int[][] colConditions) {
        // Write your solution here
        return new int[0][0];
    }
}
#include <vector>
using namespace std;

vector<vector<int>> buildMatrix(int n, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
    // Write your solution here
    return {};
}
function buildMatrix(n, rowConditions, colConditions) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Non-empty matrix despite cycles in conditionsMissing cycle detection in topological sort, producing invalid orderings.✅ Implement cycle detection using visited states in DFS or in-degree checks in Kahn's algorithm; return empty matrix if cycle detected.
Wrong: Incorrect position mapping of elements in matrixTopological order computed but positions assigned incorrectly or swapped rows and columns.✅ Map each element's position by its index in row order and column order arrays consistently.
Wrong: Empty matrix returned for n=1 with no conditionsNot handling base case n=1 properly, returning empty instead of [[1]].✅ Add explicit check for n=1 and no conditions to return [[1]].
Wrong: TLE on large inputsUsing exponential DFS or inefficient graph traversal instead of O(n+m) topological sort.✅ Use Kahn's algorithm or optimized DFS with memoization for topological sort.
✓
Test Cases
t1_01basic
Input{"n":3,"rowConditions":[[1,2],[2,3]],"colConditions":[[2,1],[3,2]]}
Expected[[0,0,1],[0,2,0],[3,0,0]]

Row order is 1->2->3, column order is 3->2->1, so 1 is at row 0 col 2, 2 at row 1 col 1, 3 at row 2 col 0.

t1_02basic
Input{"n":4,"rowConditions":[[1,3],[2,3],[3,4]],"colConditions":[[4,2],[2,1],[1,3]]}
Expected[[0,0,1,0],[0,0,0,2],[0,3,0,0],[4,0,0,0]]

Row order: 1->2->3->4; column order: 4->2->1->3; positions mapped accordingly.

t2_01edge
Input{"n":0,"rowConditions":[],"colConditions":[]}
Expected[]

Empty input n=0 means empty matrix.

t2_02edge
Input{"n":1,"rowConditions":[],"colConditions":[]}
Expected[[1]]

Single element with no conditions results in 1x1 matrix with element 1.

t2_03edge
Input{"n":3,"rowConditions":[[1,2],[2,1]],"colConditions":[]}
Expected[]

Conflicting rowConditions create a cycle, so no valid matrix exists.

t2_04edge
Input{"n":3,"rowConditions":[],"colConditions":[[1,2],[2,1]]}
Expected[]

Conflicting colConditions create a cycle, so no valid matrix exists.

t3_01corner
Input{"n":4,"rowConditions":[[1,2],[2,3],[3,4]],"colConditions":[[1,2],[2,3],[3,4]]}
Expected[[1,0,0,0],[0,2,0,0],[0,0,3,0],[0,0,0,4]]

Both row and column conditions are identical linear orders, so matrix is diagonal 1 to 4.

t3_02corner
Input{"n":3,"rowConditions":[[1,2],[2,3],[3,1]],"colConditions":[[1,3],[3,2]]}
Expected[]

Cycle in rowConditions (1->2->3->1) invalidates matrix.

t3_03corner
Input{"n":3,"rowConditions":[[1,2],[2,3]],"colConditions":[[1,2],[2,3],[3,1]]}
Expected[]

Cycle in colConditions (1->2->3->1) invalidates matrix.

t4_01performance
Input{"n":100,"rowConditions":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11],[11,12],[12,13],[13,14],[14,15],[15,16],[16,17],[17,18],[18,19],[19,20],[20,21],[21,22],[22,23],[23,24],[24,25],[25,26],[26,27],[27,28],[28,29],[29,30],[30,31],[31,32],[32,33],[33,34],[34,35],[35,36],[36,37],[37,38],[38,39],[39,40],[40,41],[41,42],[42,43],[43,44],[44,45],[45,46],[46,47],[47,48],[48,49],[49,50],[50,51],[51,52],[52,53],[53,54],[54,55],[55,56],[56,57],[57,58],[58,59],[59,60],[60,61],[61,62],[62,63],[63,64],[64,65],[65,66],[66,67],[67,68],[68,69],[69,70],[70,71],[71,72],[72,73],[73,74],[74,75],[75,76],[76,77],[77,78],[78,79],[79,80],[80,81],[81,82],[82,83],[83,84],[84,85],[85,86],[86,87],[87,88],[88,89],[89,90],[90,91],[91,92],[92,93],[93,94],[94,95],[95,96],[96,97],[97,98],[98,99],[99,100]],"colConditions":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11],[11,12],[12,13],[13,14],[14,15],[15,16],[16,17],[17,18],[18,19],[19,20],[20,21],[21,22],[22,23],[23,24],[24,25],[25,26],[26,27],[27,28],[28,29],[29,30],[30,31],[31,32],[32,33],[33,34],[34,35],[35,36],[36,37],[37,38],[38,39],[39,40],[40,41],[41,42],[42,43],[43,44],[44,45],[45,46],[46,47],[47,48],[48,49],[49,50],[50,51],[51,52],[52,53],[53,54],[54,55],[55,56],[56,57],[57,58],[58,59],[59,60],[60,61],[61,62],[62,63],[63,64],[64,65],[65,66],[66,67],[67,68],[68,69],[69,70],[70,71],[71,72],[72,73],[73,74],[74,75],[75,76],[76,77],[77,78],[78,79],[79,80],[80,81],[81,82],[82,83],[83,84],[84,85],[85,86],[86,87],[87,88],[88,89],[89,90],[90,91],[91,92],[92,93],[93,94],[94,95],[95,96],[96,97],[97,98],[98,99],[99,100]]}
⏱ Performance - must finish in 2000ms

n=100 with linear chain conditions for rows and columns; O(n+m) topological sort must complete within 2s.

Practice

(1/5)
1. You are given a directed acyclic graph (DAG) represented as an adjacency list. The task is to find all possible paths from the source node (0) to the target node (n-1). Which algorithmic approach guarantees finding all such paths efficiently without missing any, considering the graph's acyclic nature?
easy
A. Breadth-first search (BFS) that stops at the first found path to the target
B. Greedy algorithm that picks the next node with the fewest outgoing edges at each step
C. Dynamic programming with bottom-up tabulation to count the number of paths
D. Depth-first search (DFS) with backtracking to explore all paths from source to target

Solution

  1. Step 1: Understand the problem constraints

    The graph is a DAG, and we need to find all paths from source to target, not just one or count them.
  2. Step 2: Analyze algorithm suitability

    Greedy and BFS stopping at first path won't find all paths. DP counting paths doesn't return actual paths. DFS with backtracking explores all paths exhaustively, ensuring completeness.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DFS with backtracking enumerates all paths [OK]
Hint: All paths require exhaustive DFS, not greedy or BFS [OK]
Common Mistakes:
  • Assuming BFS finds all paths
  • Confusing counting paths with enumerating paths
2. Consider the following code snippet implementing the optimal solution for the largest color value in a directed graph. Given colors = "abaca" and edges = [[0,1],[0,2],[2,3],[3,4]], what is the value of max_color_value after processing all nodes?
easy
A. 3
B. 4
C. 2
D. 5

Solution

  1. Step 1: Trace dp for node 0 (color 'a')

    dp[0]['a'] = 1, max_color_value = 1
  2. Step 2: Propagate to nodes 1 and 2

    Node 1 (color 'b'): dp[1]['a'] = 1, dp[1]['b'] = 1; Node 2 (color 'a'): dp[2]['a'] = 2, max_color_value = 2
  3. Step 3: Propagate to node 3 (color 'c')

    dp[3]['a'] = 2, dp[3]['c'] = 1, max_color_value = 2
  4. Step 4: Propagate to node 4 (color 'a')

    dp[4]['a'] = 3, max_color_value = 3
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Maximum color count along path is 3 for 'a' [OK]
Hint: Track dp updates per node carefully [OK]
Common Mistakes:
  • Off-by-one in dp increments or max updates
3. 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
4. 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
5. The following code attempts to find the longest path with different adjacent characters in a DAG. Identify the line containing the subtle bug that causes incorrect results on graphs with cycles or repeated characters.
medium
A. Line with 'for node in topo_order:' loop
B. Line with 'dp = [1] * n' initialization
C. Line with 'if indegree[nei] <= 0:' condition
D. Line with 'return max(dp)' statement

Solution

  1. Step 1: Analyze indegree decrement and queue append

    The condition 'if indegree[nei] <= 0:' incorrectly allows nodes with negative indegree to be enqueued multiple times, breaking topological order.
  2. Step 2: Consequence of bug

    This causes incorrect topo_order and potentially infinite loops or wrong dp updates.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct condition should be 'indegree[nei] == 0' to enqueue once [OK]
Hint: Check indegree condition carefully for cycle detection [OK]
Common Mistakes:
  • Using <= 0 instead of == 0 for indegree check
  • Ignoring character difference in dp update
  • Incorrect dp initialization
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