Leetcode 1379 Solution

This article provides solution to leetcode question 1379 (reconstruct-a-2-row-binary-matrix)

https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix

Solution

class Solution:
    def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
        n = len(colsum)
        ans = [[0] * n, [0] * n]

        for i in range(n):
            if colsum[i] == 2:
                ans[0][i] = 1
                ans[1][i] = 1

                upper -= 1
                lower -= 1

        if upper < 0 or lower < 0:
            return []

        total_ones = 0
        for i in range(n):
            if colsum[i] == 1:
                total_ones += 1

        if total_ones != upper + lower:
            return []

        for i in range(n):
            if colsum[i] != 1:
                continue

            if upper > 0:
                ans[0][i] = 1
                upper -= 1
            else:
                ans[1][i] = 1
                lower -= 1

        return ans