Find Valid Matrix Given Row and Column Sums — LeetCode 1605 Python Solution

MediumGreedyArrayMatrix
Problem
#1605
Reading time
2 min

The problem

You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth 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.

Example

Input
rowSum = [3,8], colSum = [4,7]
Output
[[3,0],
Explanation
0th row: 3 + 0 = 3 == rowSum[0]

Python solution

Python
class Solution:
    def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
        m, n = len(rowSum), len(colSum)
        ans = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                x = min(rowSum[i], colSum[j])
                ans[i][j] = x
                rowSum[i] -= x
                colSum[j] -= x
        return ans

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1605. Find Valid Matrix Given Row and Column Sums is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1605. Find Valid Matrix Given Row and Column Sums?
LeetCode 1605. Find Valid Matrix Given Row and Column Sums is rated Medium on LeetCode.
What is the time complexity of LeetCode 1605. Find Valid Matrix Given Row and Column Sums?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1605. Find Valid Matrix Given Row and Column Sums?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1605. Find Valid Matrix Given Row and Column Sums cover?
LeetCode 1605. Find Valid Matrix Given Row and Column Sums is tagged Greedy, Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview