LeetCode 1253: Reconstruct a 2-Row Binary Matrix Solution
Master LeetCode problem 1253 (Reconstruct a 2-Row Binary Matrix), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To reconstruct the 2-row binary matrix, we can iterate through the colsum array and fill in the matrix row by row. We will start by initializing an empty matrix and then iterate through each column. At each column, we will consider the sum needed for the upper row and lower row separately. If the current column has a value of 2, we can easily assign 1 to both rows. If the current column has a value of 1, we need to be careful to ensure that the upper and lower row sums are maintained correctly. If the current column has a value of 0, we can assign 0 to both rows. Finally, if after processing all columns, the upper and lower row sums match the given values, we return the reconstructed matrix; otherwise, we return an empty matrix.
Solution Code
class Solution {
public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {
int n = colsum.length;
List<List<Integer>> matrix = new ArrayList<>();
List<Integer> upperRow = new ArrayList<>();
List<Integer> lowerRow = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (colsum[i] == 2) {
upperRow.add(1);
lowerRow.add(1);
upper--;
lower--;
} else if (colsum[i] == 1) {
if (upper > lower) {
upperRow.add(1);
lowerRow.add(0);
upper--;
} else {
upperRow.add(0);
lowerRow.add(1);
lower--;
}
} else {
upperRow.add(0);
lowerRow.add(0);
}
}
if (upper == 0 && lower == 0) {
matrix.add(upperRow);
matrix.add(lowerRow);
return matrix;
} else {
return new ArrayList<>();
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1253 (Reconstruct a 2-Row Binary Matrix)?
This page provides optimized solutions for LeetCode problem 1253 (Reconstruct a 2-Row Binary Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1253 (Reconstruct a 2-Row Binary Matrix)?
The time complexity for LeetCode 1253 (Reconstruct a 2-Row Binary Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1253 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1253 in Java, C++, or Python.