Leetcode 1605: Find Valid Matrix Given Row and Column Sums

grid47
grid47
Exploring patterns and algorithms
May 30, 2024 6 min read

You are given two arrays representing the sum of elements in each row and each column of a 2D matrix. The rowSum[i] represents the sum of the elements in the i-th row, and colSum[j] represents the sum of the elements in the j-th column. Your task is to find a matrix of non-negative integers that satisfies these row and column sum requirements.
Problem
Approach
Steps
Complexity
Input: You are provided with two arrays, rowSum and colSum, where rowSum[i] is the sum of the i-th row of a matrix and colSum[j] is the sum of the j-th column. The dimensions of the matrix are rowSum.length x colSum.length.
Example: rowSum = [5, 7], colSum = [7, 5]
Constraints:
• 1 <= rowSum.length, colSum.length <= 500
• 0 <= rowSum[i], colSum[i] <= 10^8
• sum(rowSum) == sum(colSum)
Output: Return a 2D matrix where the sum of the elements in each row equals the corresponding value in rowSum, and the sum of the elements in each column equals the corresponding value in colSum.
Example: For rowSum = [5, 7], colSum = [7, 5], one possible output could be [[0,5], [7, 0]]
Constraints:
• The matrix must be filled with non-negative integers.
Goal: To construct a matrix that satisfies both row and column sum constraints.
Steps:
• Start by initializing a 2D matrix of size rowSum.length x colSum.length, filled with zeros.
• Iterate over each element in the matrix, choosing the minimum of the remaining row sum and column sum at that position.
• Reduce the corresponding row sum and column sum by the value chosen for the matrix element.
• Repeat this process until all row and column sums are satisfied.
Goal: Given the constraints of rowSum and colSum, it is guaranteed that a valid matrix can be formed.
Steps:
• Ensure that the row sums and column sums are non-negative and satisfy the total sum equality condition.
Assumptions:
• The sum of elements in rowSum will always equal the sum of elements in colSum.
Input: Input: rowSum = [3,8], colSum = [4,7]
Explanation: In this case, the matrix should be such that the sum of the first row is 3 and the second row is 8. Similarly, the sum of the first column is 4 and the second column is 7. One possible solution is [[3, 0], [1, 7]].

Input: Input: rowSum = [5,7,10], colSum = [8,6,8]
Explanation: For this case, the matrix should be constructed such that each row sum is satisfied and each column sum is also satisfied. One possible solution is [[0,5,0], [6,1,0], [2,0,8]].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus