Reconstruct a 2-Row Binary Matrix - Problem
You're tasked with reconstructing a mysterious 2-row binary matrix from scattered clues! ๐ต๏ธโโ๏ธ
Given a matrix with n columns and exactly 2 rows, you know:
- ๐ Each cell contains only
0or1(binary matrix) - ๐ข The sum of the upper row equals
upper - ๐ข The sum of the lower row equals
lower - ๐ An array
colsum[i]telling you the sum of each column i
Your mission: Reconstruct the original 2รn matrix! If multiple valid solutions exist, return any one. If no solution is possible, return an empty array [].
Example: If upper=2, lower=1, colsum=[1,1,1], one valid matrix could be:[[1,1,0], [0,0,1]] โ
Input & Output
example_1.py โ Basic Case
$
Input:
upper = 2, lower = 1, colsum = [1,1,1]
โบ
Output:
[[1,1,0],[0,0,1]]
๐ก Note:
Upper row sum: 1+1+0=2 โ, Lower row sum: 0+0+1=1 โ, Column sums: [1,1,1] โ
example_2.py โ Impossible Case
$
Input:
upper = 1, lower = 1, colsum = [2,1,1]
โบ
Output:
[]
๐ก Note:
Column 0 needs sum=2 (both cells=1), but this would use up both row quotas, leaving no 1s for columns 1 and 2
example_3.py โ All Zeros
$
Input:
upper = 0, lower = 0, colsum = [0,0,0]
โบ
Output:
[[0,0,0],[0,0,0]]
๐ก Note:
All sums are 0, so the entire matrix is filled with zeros
Constraints
- 1 โค colsum.length โค 105
- 0 โค upper, lower โค colsum.length
- 0 โค colsum[i] โค 2 (each column can have at most 2 ones in a 2-row matrix)
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Constraints
You have row quotas (upper=2, lower=1) and column requirements (colsum=[1,1,1])
2
Greedy Assignment
For each column, if sum=2 both seats occupied; if sum=1 assign to row with remaining quota; if sum=0 both empty
3
Verify Solution
Check that all row quotas are exactly fulfilled - no over/under assignment
Key Takeaway
๐ฏ Key Insight: The greedy approach works because each column's constraint immediately determines how to fill it - we just need to track remaining row quotas and assign greedily to ensure all constraints are satisfied.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code