Problem 1605

Abstract / Summary

Given row and column sums determine if a matrix of non-negative integers exists that matches those sums.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
15 lines | 571 bytes | submitted November 28, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 rowSum does not equal the total of colSum, 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 min guarantees that no assignment ever exceeds the available capacity of either the current row or column, preventing negative values in the intermediate rowSum and colSum arrays.

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 append operations during the nested loops, reducing overhead associated with dynamic list growth.
  • The greedy selection using min eliminates 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] and rowSum[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 for loop processes each cell exactly once, leading to a straightforward traversal pattern that benefits from CPU cache locality, especially when the matrix dimensions are modest.
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.41 | σ = 1.64

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
27 links | 15 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   November 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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