Reconstruct a 2-Row Binary Matrix Problem
Description
LeetCode Problem 1253.
Given the following details of a matrix with n columns and 2 rows :
- The matrix is a binary matrix, which means each element in the matrix can be
0or1. - The sum of elements of the 0-th(upper) row is given as
upper. - The sum of elements of the 1-st(lower) row is given as
lower. - The sum of elements in the i-th column(0-indexed) is
colsum[i], wherecolsumis given as an integer array with lengthn.
Your task is to reconstruct the matrix with upper, lower and colsum.
Return it as a 2-D integer array.
If there are more than one valid solution, any of them will be accepted.
If no valid solution exists, return an empty 2-D array.
Example 1:
Input: upper = 2, lower = 1, colsum = [1,1,1]
Output: [[1,1,0],[0,0,1]]
Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.
Example 2:
Input: upper = 2, lower = 3, colsum = [2,2,1,1]
Output: []
Example 3:
Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]
Constraints:
1 <= colsum.length <= 10^50 <= upper, lower <= colsum.length0 <= colsum[i] <= 2
Solution
Approach: Count First, Then Fill
The column sums decide most of the matrix on their own:
colsum[j] = 0: both cells are 0.colsum[j] = 2: both cells are 1, so each such column uses up one 1 ofupperand one oflower.colsum[j] = 1: exactly one cell is 1, and we may pick the row.
Let twos and ones be the number of columns with sum 2 and 1. After the forced columns, the top row still needs upperLeft = upper - twos ones and the bottom row lowerLeft = lower - twos, and these must come from the sum-1 columns, one each. So a matrix exists exactly when
upperLeft >= 0andlowerLeft >= 0, andupperLeft + lowerLeft == ones.
If that holds, any split works: walk the columns, put the 1 of a sum-1 column in the top row while upperLeft > 0, and in the bottom row after that. Otherwise return an empty array. In Example 2, twos = 2 leaves upperLeft = 0 and lowerLeft = 1, but there are 2 sum-1 columns, so there is no answer.
Checking the counts before filling avoids the trap of handing out the sum-1 columns greedily and only finding out later that a sum-2 column has no 1 left in one of the rows.
Complexity: O(n) time, and O(1) extra space besides the answer, where n is the length of colsum.
class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
# A column with sum 2 takes a 1 from both rows; the columns with sum 1 share what is left.
twos = colsum.count(2)
upper_left = upper - twos
lower_left = lower - twos
if upper_left < 0 or lower_left < 0 or upper_left + lower_left != colsum.count(1):
return []
n = len(colsum)
top, bottom = [0] * n, [0] * n
for j, v in enumerate(colsum):
if v == 2:
top[j] = bottom[j] = 1
elif v == 1:
if upper_left > 0:
top[j] = 1
upper_left -= 1
else:
bottom[j] = 1
return [top, bottom]