← Home

1072. Flip Columns For Maximum Number of Equal Rows

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
107

The trick here is to name the state correctly, then let the implementation follow. For 1072. Flip Columns For Maximum Number of Equal Rows, the solution in this repository is mainly a straightforward implementation 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: straightforward implementation.

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

  • TLE

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are all0, all1, allSame, maxEqualRowsAfterFlips, sum.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • 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. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

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(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02
03class Solution {
04public:
05    bool all0(vector<int>& arr){
06        return accumulate(arr.begin(), arr.end(), 0) == 0;
07    };
08    
09    bool all1(vector<int>& arr){
10        return accumulate(arr.begin(), arr.end(), 1, multiplies<int>()) == 1;
11    };
12    
13    bool allSame(vector<int>& arr1, vector<int>& arr2){
14        bool flag = true;
15        for(int i = 0; i < arr1.size(); i++){
16            if(arr1[i] != arr2[i]){
17                flag = false;
18                break;
19            }
20        }
21        return flag;
22    };
23    
24    int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
25        int m = matrix.size(), n = matrix[0].size();
26        vector<int> sum(n), reverted(n), ones(n, 1);
27        int ans = 0;
28        
29        for(int i = 0; i < m; i++){
30            set<vector<int>> group;
31            int row_friend = 0;
32            for(int j = 0; j < m; j++){
33                if(j == i) continue;
34                //sum two vector element-wise
35                transform(matrix[i].begin(), matrix[i].end(),
36                    matrix[j].begin(), sum.begin(), plus<int>());
37                //if their sum is all 0 or all 1, 
38                //row_friend++
39                if(allSame(matrix[i], matrix[j]) || all1(sum)){
40                // if(all1(sum)){
41                    //ensure the 0th element is 0 and then record it into the set
42                    reverted = matrix[i];
43                    if(matrix[i][0] != 0){
44                        transform(ones.begin(), ones.end(), matrix[i].begin(), reverted.begin(), minus<int>());
45                    }
46                    if(group.find(reverted) == group.end()){
47                        row_friend += 2;
48                    }else{
49                        row_friend++;
50                    }
51                    group.insert(reverted);
52                }
53            }
54            ans = max(ans, row_friend);
55        }
56        
57        if(ans == 0){
58            for(int i = 0; i < m; i++){
59                if(all0(matrix[i]) || all1(matrix[i])){
60                // if(all1(matrix[i])){
61                    ans++;
62                }
63            }
64        }
65        
66        //we can always do custom operations for a specific row
67        if(ans == 0) ans = 1;
68        
69        return ans;
70    }
71};
72
73//https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/303897/Java-easy-solution-%2B-explanation
74//Runtime: 1620 ms, faster than 5.34% of C++ online submissions for Flip Columns For Maximum Number of Equal Rows.
75//Memory Usage: 26.7 MB, less than 100.00% of C++ online submissions for Flip Columns For Maximum Number of Equal Rows.
76class Solution {
77public:
78    bool all1(vector<int>& arr){
79        return accumulate(arr.begin(), arr.end(), 1, multiplies<int>()) == 1;
80    };
81    
82    bool allSame(vector<int>& a, vector<int>& b){
83        bool flag = true;
84        for(int i = 0; i < a.size(); i++){
85            if(a[i] != b[i]){
86                flag = false;
87                break;
88            }
89        }
90        return flag;
91    };
92    
93    int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
94        int m = matrix.size(), n = matrix[0].size();
95        int ans = 0;
96        vector<int> sum(n);
97        vector<int> reversed(n);
98        
99        for(int i = 0; i < m; i++){
100            int row_friend = 0;
101            for(int j = 0; j < m; j++){
102                // transform(matrix[i].begin(), matrix[i].end(), matrix[j].begin(), sum.begin(), plus<int>());
103                for(int k = 0; k < n; k++){
104                    reversed[k] = 1 - matrix[j][k];
105                }
106                // if(allSame(matrix[i], matrix[j]) || all1(sum)){
107                // if(allSame(matrix[i], matrix[j]) || allSame(matrix[i], reversed)){
108                if(matrix[i] == matrix[j] || matrix[i] == reversed){
109                    row_friend++;
110                }
111            }
112            //row_friend's minimum is 1
113            ans = max(ans, row_friend);
114        }
115        
116        return ans;
117    }
118};
119
120//speed the solution above with a set
121//Runtime: 632 ms, faster than 9.71% of C++ online submissions for Flip Columns For Maximum Number of Equal Rows.
122//Memory Usage: 27.4 MB, less than 100.00% of C++ online submissions for Flip Columns For Maximum Number of Equal Rows.
123class Solution {
124public:
125    int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
126        int m = matrix.size(), n = matrix[0].size();
127        int ans = 0;
128        vector<int> sum(n);
129        vector<int> reversed(n);
130        set<int> grouped;
131        
132        for(int i = 0; i < m; i++){
133            int row_friend = 0;
134            //skip rows that can be grouped to earlier rows
135            if(grouped.find(i) != grouped.end()) continue;
136            for(int j = 0; j < m; j++){
137                for(int k = 0; k < n; k++){
138                    reversed[k] = 1 - matrix[j][k];
139                }
140                if(matrix[i] == matrix[j] || matrix[i] == reversed){
141                    row_friend++;
142                    grouped.insert(i);
143                    grouped.insert(j);
144                }
145            }
146            //row_friend's minimum is 1
147            ans = max(ans, row_friend);
148        }
149        
150        return ans;
151    }
152};
153
154//use a map
155//https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/303752/Python-1-Line
156//Runtime: 212 ms, faster than 50.49% of C++ online submissions for Flip Columns For Maximum Number of Equal Rows.
157//Memory Usage: 44.7 MB, less than 100.00% of C++ online submissions for Flip Columns For Maximum Number of Equal Rows.
158class Solution {
159public:
160    int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
161        int m = matrix.size(), n = matrix[0].size();
162        map<vector<int>, int> counter;
163        vector<int> ones(n, 1), reversed(n);
164        
165        for(int i = 0; i < matrix.size(); i++){
166            transform(ones.begin(), ones.end(), matrix[i].begin(), reversed.begin(), minus<int>());
167            counter[matrix[i]]++;
168            counter[reversed]++;
169        }
170        
171        auto it = max_element(counter.begin(), counter.end(), 
172            [](const pair<vector<int>, int> & p1, const pair<vector<int>, int> & p2){
173            return p1.second < p2.second;
174        });
175
176        return it->second;
177    }
178};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
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.