Sponsored
Sponsored
The greedy approach involves iterating over the matrix and at each cell (i, j), filling it with the minimum of the current rowSum[i] and colSum[j]. This method works because as we fill the matrix, we can always satisfy both the row and column conditions by subtracting the filled value from each.
Move through the matrix, adjusting row and column sums at each step. This continues until we've filled the entire matrix, ensuring the integrity of both row and column sum conditions.
Time Complexity: O(m + n), where m and n are the lengths of rowSum and colSum respectively, as we're adjusting values once per index.
Space Complexity: O(m * n) for storing the matrix.
1def restoreMatrix(rowSum, colSum):
2 m = len(rowSum)
3 n = len(colSum)
4 matrix = [[0] * n for _ in range(m)]
5 i, j = 0, 0
6 while i < m and j < n:
7 fill = min(rowSum[i], colSum[j])
8 matrix[i][j] = fill
9 rowSum[i] -= fill
10 colSum[j] -= fill
11 if rowSum[i] == 0:
12 i += 1
13 if colSum[j] == 0:
14 j += 1
15 return matrix
This solution creates a matrix with dimensions based on the rowSum and colSum lists. It iteratively assigns to each cell matrix[i][j] the minimum of current rowSum[i] and colSum[j], ensuring non-negativity and consistency with both row and column requirements. The indices i and j are incremented appropriately to iterate through all cells.