LeetCode 1253: Reconstruct a 2-Row Binary Matrix
LeetCode 1253 Solution 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.
LeetCode 1253 Solutions in Java, C++, Python
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<>();
}
}
}
Interactive Code Editor for LeetCode 1253
Improve Your LeetCode 1253 Solution
Use the editor below to refine the provided solution for LeetCode 1253. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...