Solving Leetcode Interviews in Seconds with AI: Build a Matrix With Conditions
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2392" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given a positive integer k. You are also given: a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti]. The two arrays contain integers from 1 to k. You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0. The matrix should also satisfy the following conditions: The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1. The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1. Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix. Example 1: Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] Output: [[3,0,0],[0,0,1],[0,2,0]] Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions. The row conditions are the following: - Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. - Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. The column conditions are the following: - Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. - Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. Note that there may be multiple correct answers. Example 2: Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]] Output: [] Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied. No matrix can satisfy all the conditions, so we return the empty matrix. Constraints: 2 <= k <= 400 1 <= rowConditions.length, colConditions.length <= 104 rowConditions[i].length == colConditions[i].length == 2 1 <= abovei, belowi, lefti, righti <= k abovei != belowi lefti != righti
Explanation
Here's the breakdown of the solution:
- Topological Sort: The core idea is to use topological sort to determine the correct row and column order based on the given conditions. We construct graphs representing the row and column dependencies and then perform topological sorting.
- Matrix Construction: If the topological sorts are successful (no cycles), we use the resulting row and column orders to place the numbers 1 to
kin thek x kmatrix. Cycle Detection: If a cycle exists in either the row or column dependencies, it signifies a contradiction in the conditions, and we return an empty matrix.
Time & Space Complexity: O(k + n + m + k^2) time, O(k + n + m + k^2) space, where
nis the number of row conditions,mis the number of column conditions, andkis the dimension of the matrix.
Code
def build_matrix(k: int, rowConditions: list[list[int]], colConditions: list[list[int]]) -> list[list[int]]:
"""
Builds a k x k matrix satisfying row and column conditions.
Args:
k: The size of the matrix.
rowConditions: Row conditions (above, below).
colConditions: Column conditions (left, right).
Returns:
A k x k matrix satisfying the conditions, or an empty matrix if no solution exists.
"""
def topological_sort(conditions: list[list[int]], k: int) -> list[int]:
"""Performs topological sort on the given conditions."""
graph = [[] for _ in range(k + 1)]
in_degree = [0] * (k + 1)
for u, v in conditions:
graph[u].append(v)
in_degree[v] += 1
queue = [i for i in range(1, k + 1) if in_degree[i] == 0]
result = []
while queue:
u = queue.pop(0)
result.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
if len(result) != k: # Cycle detected
return []
return result
row_order = topological_sort(rowConditions, k)
col_order = topological_sort(colConditions, k)
if not row_order or not col_order:
return []
row_pos = {num: i for i, num in enumerate(row_order)}
col_pos = {num: i for i, num in enumerate(col_order)}
matrix = [[0] * k for _ in range(k)]
for num in range(1, k + 1):
row = row_pos[num]
col = col_pos[num]
matrix[row][col] = num
return matrix