← Home

1605. Find Valid Matrix Given Row and Column Sums

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
160

Let's make this one less mysterious. For 1605. Find Valid Matrix Given Row and Column Sums, the solution in this repository is mainly a greedy solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • Greedy: each time fill the cell pointed by min rowSum and min colSum

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(mn), space: O(mn)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Greedy: each time fill the cell pointed by min rowSum and min colSum
02//Runtime: 140 ms, faster than 12.50% of C++ online submissions for Find Valid Matrix Given Row and Column Sums.
03//Memory Usage: 33.6 MB, less than 25.00% of C++ online submissions for Find Valid Matrix Given Row and Column Sums.
04class Solution {
05public:
06    vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
07        int m = rowSum.size(), n = colSum.size();
08        vector<vector<int>> mat(m, vector<int>(n, 0));
09        
10        do{
11            int min_row = min_element(rowSum.begin(), rowSum.end()) - rowSum.begin();
12            int min_col = min_element(colSum.begin(), colSum.end()) - colSum.begin();
13            
14            // cout << min_row << ", " << min_col << endl;
15            
16            if((rowSum[min_row] == INT_MAX) && (colSum[min_col] == INT_MAX)) break;
17            
18            int val = min(rowSum[min_row], colSum[min_col]);
19            
20            // cout << "val: " << val << endl;
21            
22            mat[min_row][min_col] = val;
23            rowSum[min_row] -= val; if(rowSum[min_row] == 0) rowSum[min_row] = INT_MAX;
24            colSum[min_col] -= val; if(colSum[min_col] == 0) colSum[min_col] = INT_MAX;
25            
26            // cout << "rowSum" << endl;
27            // for(int i = 0; i < m; ++i){
28            //     cout << rowSum[i] << " ";
29            // }
30            // cout << endl;
31            
32            // cout << "colSum" << endl;
33            // for(int j = 0; j < n; ++j){
34            //     cout << colSum[j] << " ";
35            // }
36            // cout << endl;
37        }while(true);
38        
39        return mat;
40    }
41};
42
43//Greedy
44//https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/876845/JavaC%2B%2BPython-Easy-and-Concise-with-Prove
45//Runtime: 108 ms, faster than 50.00% of C++ online submissions for Find Valid Matrix Given Row and Column Sums.
46//Memory Usage: 33.8 MB, less than 25.00% of C++ online submissions for Find Valid Matrix Given Row and Column Sums.
47//time: O(mn), space: O(mn)
48class Solution {
49public:
50    vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
51        int m = rowSum.size();
52        int n = colSum.size();
53        
54        vector<vector<int>> mat(m, vector<int>(n, 0));
55        
56        for(int i = 0; i < m; ++i){
57            for(int j = 0; j < n; ++j){
58                mat[i][j] = min(rowSum[i], colSum[j]);
59                rowSum[i] -= mat[i][j];
60                colSum[j] -= mat[i][j];
61            }
62        }
63        
64        return mat;
65    }
66};
67
68//Greedy
69//https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/876845/JavaC%2B%2BPython-Easy-and-Concise-with-Prove
70//Runtime: 76 ms, faster than 75.00% of C++ online submissions for Find Valid Matrix Given Row and Column Sums.
71//Memory Usage: 33.6 MB, less than 25.00% of C++ online submissions for Find Valid Matrix Given Row and Column Sums.
72//time: O(mn) for initialization, O(m+n) for process, space: O(mn)
73class Solution {
74public:
75    vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
76        int m = rowSum.size();
77        int n = colSum.size();
78        
79        vector<vector<int>> mat(m, vector<int>(n, 0));
80        
81        int i = 0, j = 0;
82        
83        while(i < m && j < n){
84            mat[i][j] = min(rowSum[i], colSum[j]);
85            rowSum[i] -= mat[i][j];
86            colSum[j] -= mat[i][j];
87            //done for ith row
88            if(rowSum[i] == 0) ++i;
89            //done for jth col
90            if(colSum[j] == 0) ++j;
91        }
92        
93        return mat;
94    }
95};

Cost

Complexity

Time
O(mn), space: O(mn)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.