Leetcode 1253: Reconstruct a 2-Row Binary Matrix

grid47
grid47
Exploring patterns and algorithms
Jul 4, 2024 6 min read

You are given a binary matrix with 2 rows and n columns, where each element is either 0 or 1. The sum of elements in the 0-th (upper) row is given by upper, the sum of elements in the 1-st (lower) row is given by lower, and the column-wise sum is given by colsum. Your task is to reconstruct the matrix based on these sums. If reconstruction is not possible, return an empty matrix.
Problem
Approach
Steps
Complexity
Input: The input consists of three integers: upper, lower, and a list colsum representing the column-wise sums.
Example: upper = 2, lower = 1, colsum = [1,1,1]
Constraints:
• 1 <= colsum.length <= 10^5
• 0 <= upper, lower <= colsum.length
• 0 <= colsum[i] <= 2
Output: Return the reconstructed matrix if valid; otherwise, return an empty matrix.
Example: [[1, 1, 0], [0, 0, 1]]
Constraints:
• The reconstructed matrix must satisfy the row and column sums.
• If no valid solution exists, return an empty matrix.
Goal: Reconstruct a valid binary matrix by ensuring that row and column sums match the given constraints.
Steps:
• Iterate through the colsum array to reconstruct the matrix by assigning values to the two rows based on the constraints.
• Ensure that the values assigned to the rows satisfy the given upper and lower row sums as well as the colsum constraints.
Goal: The constraints specify that the size of the colsum array can be up to 100,000, and the values for upper and lower are non-negative and bounded by the length of the colsum array.
Steps:
• 1 <= colsum.length <= 10^5
• 0 <= upper, lower <= colsum.length
• 0 <= colsum[i] <= 2
Assumptions:
• The input values are valid and the row sums upper and lower are feasible with respect to colsum.
Input: upper = 2, lower = 1, colsum = [1, 1, 1]
Explanation: The matrix is valid as the sums of the rows and columns match the given values.

Input: upper = 2, lower = 3, colsum = [2, 2, 1, 1]
Explanation: It is impossible to reconstruct a valid matrix, as the lower row sum exceeds the total sum of the columns.

Input: upper = 5, lower = 5, colsum = [2, 1, 2, 0, 1, 0, 1, 2, 0, 1]
Explanation: The matrix is reconstructed correctly, with the row and column sums matching the given values.

Link to LeetCode Lab


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