bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1253. Reconstruct a 2-Row Binary Matrix

1253. Reconstruct a 2-Row Binary Matrix

Leetcode Solutions

Greedy Approach with Early Validation

  1. Check if the sum of colsum is equal to upper + lower. If not, return an empty array.
  2. Count the number of 2s in colsum. If this count is greater than upper or lower, return an empty array.
  3. Initialize two arrays, upperRow and lowerRow, with zeros.
  4. Iterate through colsum: a. If colsum[i] == 2, set upperRow[i] and lowerRow[i] to 1, and decrement both upper and lower. b. If colsum[i] == 1, preferentially assign 1 to upperRow if upper > lower, otherwise assign to lowerRow, and decrement the corresponding upper or lower.
  5. If after the iteration upper or lower is not zero, return an empty array.
  6. Return the matrix composed of upperRow and lowerRow.
UML Thumbnail

Backtracking Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...