Find Valid Matrix Given Row and Column Sums

Medium Topics Company Tags

Construct a matrix of nonnegative integers using the requested row sums in rowSum and column sums in colSum. The matrix must have rowSum.length rows and colSum.length columns.

The sum of row i must equal rowSum[i], and the sum of column j must equal colSum[j]. Return any matrix satisfying these conditions. The total of rowSum equals the total of colSum, so a valid matrix always exists.

Example 1:

Input: rowSum = [4,6]
colSum = [3,7]

Output: [[3,1],[0,6]]

Explanation: For [[3,1],[0,6]], the row sums are 4 and 6, and the column sums are 3 and 7. All entries are nonnegative.

Example 2:

Input: rowSum = [0,5]
colSum = [2,3]

Output: [[0,0],[2,3]]

Explanation: The first row must contain only zeros. Placing 2 and 3 in the second row satisfies both column sums and the second row sum of 5.

Example 3:

Input: rowSum = [2,2]
colSum = [2,2]

Output: [[2,0],[0,2]]

Explanation: The matrix [[2,0],[0,2]] has every row and column sum equal to 2. The matrix [[1,1],[1,1]] is another accepted answer.

Constraints:

  • 1 <= rowSum.length, colSum.length <= 500
  • 0 <= rowSum[i], colSum[j] <= 100000000
  • sum(rowSum) == sum(colSum)


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.