Find Valid Matrix Given Row and Column Sums - Problem
You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the i-th row and colSum[j] is the sum of the elements of the j-th column of a 2D matrix.
In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.
Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.
Input & Output
Example 1 — Basic Case
$
Input:
rowSum = [3,8], colSum = [4,7]
›
Output:
[[0,3],[4,4]]
💡 Note:
Row 0: 0+3=3 ✓, Row 1: 4+4=8 ✓, Col 0: 0+4=4 ✓, Col 1: 3+4=7 ✓
Example 2 — Square Matrix
$
Input:
rowSum = [5,7,10], colSum = [8,6,8]
›
Output:
[[0,5,0],[6,1,0],[2,0,8]]
💡 Note:
Each row sum and column sum matches the requirements. Greedy approach fills optimally.
Example 3 — Single Row
$
Input:
rowSum = [14], colSum = [9,5]
›
Output:
[[9,5]]
💡 Note:
Single row case: 9+5=14 ✓, columns sum to [9] and [5] respectively.
Constraints
- 1 ≤ rowSum.length, colSum.length ≤ 500
- 0 ≤ rowSum[i], colSum[i] ≤ 108
- sum(rowSum) == sum(colSum)
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given rowSum=[3,8] and colSum=[4,7] - need 2x2 matrix
2
Process
Greedily fill each cell with min(remaining_row, remaining_col)
3
Output
Result matrix [[0,3],[4,4]] satisfies all constraints
Key Takeaway
🎯 Key Insight: Greedy approach works because placing min(remaining_row, remaining_col) at each position ensures we never exceed constraints while guaranteeing a solution exists.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code