Skip to main content
LeetCode 1605, Medium. Topics: Array, Greedy, Matrix, Flow Network. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 19 parametrized pytest cases, and a playground notebook:

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<sup>th</sup> row and colSum[j] is the sum of the elements of the j<sup>th</sup> 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.

Examples

Constraints

  • 1 <= rowSum.length, colSum.length <= 500
  • 0 <= rowSum[i], colSum[i] <= 10^8
  • sum(rowSum) == sum(colSum)

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026