Reconstruct a 2-Row Binary Matrix - Problem
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.
Input & Output
Example 1 — Basic Valid Case
$
Input:
upper = 1, lower = 1, colsum = [1,1,0]
›
Output:
[[1,0,0],[0,1,0]]
💡 Note:
Column 0 needs sum 1: place 1 in upper row. Column 1 needs sum 1: place 1 in lower row. Column 2 needs sum 0: both rows get 0. Row sums: upper=1, lower=1 ✓
Example 2 — Column Sum 2
$
Input:
upper = 2, lower = 1, colsum = [2,1,0]
›
Output:
[[1,1,0],[1,0,0]]
💡 Note:
Column 0 needs sum 2: place 1 in both rows. Column 1 needs sum 1: place 1 in upper row (has higher remaining quota). Column 2 needs sum 0. Final sums: upper=2, lower=1 ✓
Example 3 — Impossible Case
$
Input:
upper = 1, lower = 1, colsum = [2,2,0]
›
Output:
[]
💡 Note:
Column sums total 4 but upper+lower=2. Impossible to satisfy both constraints, so return empty array.
Constraints
- 1 ≤ colsum.length ≤ 105
- 0 ≤ upper, lower ≤ colsum.length
- 0 ≤ colsum[i] ≤ 2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Row sums (upper=1, lower=1) and column sums [1,1,0]
2
Process
Greedily assign 1s to satisfy both row and column constraints
3
Output
Valid 2×3 binary matrix [[1,0,0],[0,1,0]]
Key Takeaway
🎯 Key Insight: Each column sum dictates exactly how many 1s it needs - use greedy quota tracking
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code