Python 1605.py
class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
width = len(colSum)
height = len(rowSum)
result = [ [ 0 ] * width for _ in range(height) ]
for x in range(width):
for y in range(height):
# select the largest value such that colsum and rownum are still non-negative
low = min(colSum[x], rowSum[y])
result[y][x] = low
colSum[x] -= low
rowSum[y] -= low
return result
Difficulty
and has an acceptance rate of about 83% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method restoreMatrix. The method receives two integer arrays, rowSum and colSum, and constructs a two-dimensional matrix whose rows and columns sum to the given values. The algorithm proceeds by iterating over each column and, within that, over each row, greedily assigning the maximum feasible value to each cell while keeping the remaining row and column sums non-negative. The final matrix is returned as a list of lists.
Key Steps
Initialization
width = len(colSum)
height = len(rowSum)
result = [ [ 0 ] * width for _ in range(height) ]
The code first determines the dimensions of the target matrix: the number of columns equals the length of colSum, and the number of rows equals the length of rowSum. It then creates a matrix filled with zeros, using a list comprehension that replicates a row of zeros height times. This pre-allocation ensures that each cell can be updated in place without additional resizing.
Iterative Filling
for x in range(width):
for y in range(height):
low = min(colSum[x], rowSum[y])
result[y][x] = low
colSum[x] -= low
rowSum[y] -= low
The outer loop iterates over column indices (x), while the inner loop walks through row indices (y). For each cell (y, x), the algorithm computes low as the smaller of the remaining column sum colSum[x] and the remaining row sum rowSum[y]. This value is the largest amount that can be placed in the current cell without causing either the row or column total to drop below zero. The cell is then set to low, and the corresponding entries in colSum and rowSum are decremented by that amount, reflecting the consumption of the allocated value.
Return
return result
After all cells have been processed, the fully populated matrix is returned. At this point, the remaining entries in rowSum and colSum are all zero, indicating that the constructed matrix satisfies the required row and column sums.
Edge Cases Handled
The algorithm naturally accommodates several edge conditions:
- When a row sum is zero from the start,
min(colSum[x], rowSum[y])yields zero for every column in that row, leaving the entire row as zeros. The decrement operations have no effect, preserving the invariant that row sums remain non-negative. - Similarly, if a column sum is zero initially, the inner loop assigns zero to every cell in that column, and the column sum stays at zero throughout the process.
- If the total of
rowSumdoes not equal the total ofcolSum, the greedy allocation still proceeds without error; the final matrix will reflect the maximal feasible distribution given the mismatched totals, and the remaining sums will be non-negative after each step. - The use of
minguarantees that no assignment ever exceeds the available capacity of either the current row or column, preventing negative values in the intermediaterowSumandcolSumarrays.
Performance Optimizations
The implementation exhibits a few deliberate choices that contribute to efficient execution:
- Pre-allocating the result matrix with a single list comprehension avoids repeated
appendoperations during the nested loops, reducing overhead associated with dynamic list growth. - The greedy selection using
mineliminates the need for additional data structures or look-ahead logic; each cell is resolved in constant time based on the current state of the row and column sums. - Updating
colSum[x]androwSum[y]in place removes the necessity for auxiliary copies, keeping memory usage low and ensuring that subsequent iterations work with the most recent residual sums. - The double
forloop processes each cell exactly once, leading to a straightforward traversal pattern that benefits from CPU cache locality, especially when the matrix dimensions are modest.
ELI5 - Simplified Explanation
Imagine a big blank grid of empty squares like a game board. There are some bags of colorful marbles sitting next to the rows and columns. Each bag tells how many marbles belong in that specific row or column. The goal is to fill the empty squares with marbles so that every row and column has exactly the right number.
The code looks at the first square and checks how many marbles the row needs and how many the column needs. To be fair, it takes the smallest of those two numbers and puts that many marbles into the square. Once those marbles are put down, they are taken away from the bags for that row and that column. This process repeats for every single square on the board, moving along one by one. By the time every square has been checked, the grid is perfectly filled with all the right amounts of marbles in every row and column, just like solving a fun puzzle.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | JS | Java | Go | TS | ||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1253: Reconstruct a 2-Row Binary Matrix
Solved On The Same Day
- problem 1217: Minimum Cost to Move Chips to The Same Position
- problem 1221: Split a String in Balanced Strings
- problem 1323: Maximum 69 Number
- problem 1710: Maximum Units on a Truck
- problem 969: Pancake Sorting
- problem 991: Broken Calculator
- problem 630: Course Schedule III
- problem 1425: Constrained Subsequence Sum
- problem 2147: Number of Ways to Divide a Long Corridor
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality