Problem Description
Given a 2-row binary matrix with n columns, reconstruct the matrix given the row sums (upper and lower) and an array colsum where colsum[i] is the sum of the two entries in the i-th column. Each column’s sum can be 0, 1, or 2. A column with a sum of 2 forces both rows to have a 1 at that column. For columns with a sum of 1, assign the single 1 to an appropriate row based on the remaining required row sum. If no valid assignment exists, return an empty matrix.
Key Insights
- Columns with colsum = 2 must have both rows set to 1, which decreases both the upper and lower remaining sums.
- Columns with colsum = 0 are trivially assigned as 0 in both rows.
- For columns with colsum = 1, a greedy approach is used: assign the 1 to the upper row if it still needs ones; otherwise, use the lower row.
- After processing all columns, both upper and lower needs should exactly meet 0. Any mismatch indicates an invalid configuration.
Space and Time Complexity
Time Complexity: O(n) – iterate through the colsum array once (or twice in case of two passes). Space Complexity: O(n) – storing the final result matrix with 2 rows and n columns.
Solution
The solution follows a two-pass strategy. In the first pass, process all columns with colsum = 2 by setting both rows to 1 (and updating the upper and lower counts accordingly). In the second pass, process columns with colsum = 1: assign the 1 to the upper row if possible; otherwise, assign it to the lower row. If at any step the remaining upper or lower counts become negative, or if after all assignments the counts do not exactly drop to 0, the reconstruction is impossible and an empty array is returned.