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
Find Valid Matrix Given Row and Column Sums INPUT rowSum = [3, 8] 3 8 Row 0, Row 1 colSum = [4, 7] 4 7 Col 0, Col 1 Matrix Template (2x2) ? ? ? ? R0 R1 C0 C1 ALGORITHM STEPS 1 Cell [0,0]: min(3,4)=0 Set matrix[0][0]=0 rowSum[0]=3, colSum[0]=4 2 Cell [0,1]: min(3,7)=3 Set matrix[0][1]=3 rowSum[0]=0, colSum[1]=4 3 Cell [1,0]: min(8,4)=4 Set matrix[1][0]=4 rowSum[1]=4, colSum[0]=0 4 Cell [1,1]: min(4,4)=4 Set matrix[1][1]=4 rowSum[1]=0, colSum[1]=0 Greedy Formula: val = min(rowSum[i], colSum[j]) Process cells row by row Update sums after each fill FINAL RESULT Output Matrix: 0 3 4 4 =3 OK =8 OK =4 OK =7 OK Output: [[0, 3], [4, 4]] Verification: Row 0: 0+3 = 3 Row 1: 4+4 = 8 Col 0: 0+4 = 4 Col 1: 3+4 = 7 All Constraints Met! Key Insight: The greedy approach works because taking min(rowSum[i], colSum[j]) guarantees we never exceed either constraint. By subtracting the value from both sums, we maintain the invariant that remaining sums equal remaining cell requirements. Time: O(m*n) | Space: O(m*n) for the result matrix. TutorialsPoint - Find Valid Matrix Given Row and Column Sums | Greedy Approach
Asked in
Google 12 Amazon 8 Microsoft 6
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen