Reconstruct a 2-Row Binary Matrix — LeetCode 1253 Python Solution
- Problem
- #1253
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- upper = 2, lower = 1, colsum = [1,1,1]
- Output
- [[1,1,0],[0,0,1]]
- Explanation
- [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.
Python solution
class Solution:
def reconstructMatrix(
self, upper: int, lower: int, colsum: List[int]
) -> List[List[int]]:
n = len(colsum)
ans = [[0] * n for _ in range(2)]
for j, v in enumerate(colsum):
if v == 2:
ans[0][j] = ans[1][j] = 1
upper, lower = upper - 1, lower - 1
if v == 1:
if upper > lower:
upper -= 1
ans[0][j] = 1
else:
lower -= 1
ans[1][j] = 1
if upper < 0 or lower < 0:
return []
return ans if lower == upper == 0 else []Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array colsum |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1253. Reconstruct a 2-Row Binary Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1253. Reconstruct a 2-Row Binary Matrix?
- LeetCode 1253. Reconstruct a 2-Row Binary Matrix is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1253. Reconstruct a 2-Row Binary Matrix?
- The Python solution on this page runs in O(n), where n is the length of the array colsum.
- What is the space complexity of LeetCode 1253. Reconstruct a 2-Row Binary Matrix?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1253. Reconstruct a 2-Row Binary Matrix cover?
- LeetCode 1253. Reconstruct a 2-Row Binary Matrix is tagged Greedy, Array and Matrix on LeetCode.