#1253

Reconstruct a 2-Row Binary Matrix

Medium
ArrayGreedyMatrixGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution directly fills the matrix based on the values in colsum, ensuring we respect the constraints for upper and lower sums without unnecessary checks. This is efficient and straightforward.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a 2D array of size 2 x n with all zeros.
  2. 2Step 2: Iterate through each column in colsum.
  3. 3Step 3: For each column, if colsum[i] is 2, fill both rows with 1 and decrease upper and lower accordingly; if colsum[i] is 1, fill the upper row if possible, otherwise fill the lower row.
  4. 4Step 4: After filling, check if upper and lower are both zero; if so, return the result, otherwise return an empty array.
solution.py19 lines
1# Full working Python code
2
3def reconstructMatrix(upper, lower, colsum):
4    n = len(colsum)
5    result = [[0] * n for _ in range(2)]
6    for i in range(n):
7        if colsum[i] == 2:
8            result[0][i] = 1
9            result[1][i] = 1
10            upper -= 1
11            lower -= 1
12        elif colsum[i] == 1:
13            if upper > 0:
14                result[0][i] = 1
15                upper -= 1
16            else:
17                result[1][i] = 1
18                lower -= 1
19    return result if upper == 0 and lower == 0 else []

Complexity note: The complexity is O(n) because we only make a single pass through the colsum array, filling the matrix based on the conditions.

  • 1The sum of colsum must equal the total of upper and lower for a valid solution.
  • 2Filling the matrix based on the constraints of colsum ensures that we respect the limits of upper and lower.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.