#1605

Find Valid Matrix Given Row and Column Sums

Medium
ArrayGreedyMatrixGreedyMatrix Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach is essentially the same as the brute-force method, but it emphasizes the greedy nature of filling the matrix. By always placing the minimum of the remaining row and column sums, we ensure that we efficiently meet the requirements without unnecessary iterations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a 2D matrix of size rowSum.length x colSum.length with all zeros.
  2. 2Step 2: Iterate through each cell in the matrix using two nested loops.
  3. 3Step 3: For each cell, assign the minimum of the current rowSum and colSum, then update both rowSum and colSum.
solution.py12 lines
1# Full working Python code
2
3def fillMatrix(rowSum, colSum):
4    m, n = len(rowSum), len(colSum)
5    matrix = [[0] * n for _ in range(m)]
6    for i in range(m):
7        for j in range(n):
8            value = min(rowSum[i], colSum[j])
9            matrix[i][j] = value
10            rowSum[i] -= value
11            colSum[j] -= value
12    return matrix

Complexity note: The time complexity remains O(n²) due to the nested loops, but the approach is optimal in terms of efficiency since it directly satisfies the conditions without unnecessary checks. The space complexity is O(n) for storing the matrix.

  • 1The sum of row sums must equal the sum of column sums.
  • 2Greedily choosing the minimum of row and column sums ensures we meet the requirements efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.