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 Target Matrix Structure ? ? ? ? ? ? Row0 Row1 Col0 Col1 Col2 upper = 1 lower = 1 colsum = [1, 1, 0] Each cell: 0 or 1 Row sums must match Col sums must match ALGORITHM STEPS 1 Handle colsum = 2 Set both rows to 1 upper--, lower-- 2 Handle colsum = 0 Set both rows to 0 No change to sums 3 Handle colsum = 1 Greedy: prefer upper if upper > 0, else lower 4 Validate Check upper==0 and lower==0 at end Processing Example: Col0:1 Col1:1 Col2:0 u:1 u:0 u:0 l:1 l:0 l:0 FINAL RESULT Reconstructed Matrix 1 0 0 0 1 0 =1 OK =1 OK =1 =1 =0 Output: [[1,0,0],[0,1,0]] Verification: Row0 sum: 1+0+0 = 1 OK Row1 sum: 0+1+0 = 1 OK Colsums: [1,1,0] OK Key Insight: Process columns greedily: First handle colsum=2 (must fill both rows), then colsum=0 (must leave empty), finally colsum=1 (choose row with remaining capacity). This greedy approach works because each column decision is independent and locally optimal. Time: O(n), Space: O(n) for result matrix. TutorialsPoint - Reconstruct a 2-Row Binary Matrix | Greedy Column-by-Column Approach
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