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 0 or 1.
  • 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], where colsum is given as an integer array with length n.

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
Reconstruct 2-Row Binary Matrix: Input → Process → OutputINPUT CONSTRAINTSupper = 1 (row 0 sum)lower = 1 (row 1 sum)colsum = [1,1,0]110Column Sum RequirementsGREEDY PROCESS1. Col 0: sum=1, assign to upper2. Col 1: sum=1, assign to lower3. Col 2: sum=0, both get 0100010110VALID OUTPUT[[1,0,0],[0,1,0]]100010110= 1 ✓= 1 ✓Row sums: [1,1] ✓ | Column sums: [1,1,0] ✓Greedy assignment satisfies all constraints in O(n) time
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
Asked in
Google 15 Facebook 12 Amazon 8
32.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen