Flip Columns For Maximum Number of Equal Rows

Two rows become identical after some column flips iff they're equal or exact complements; bucket-count both forms.

Medium
Time O(m*n) Space O(m*n)
LeetCode
3 min read
matrix hashing

Problem#

Given a binary m x n matrix, you may flip any subset of columns (toggle all bits in each chosen column). Return the maximum number of rows that can be made identical after some choice of flips.

Examples#

  • [[0,1],[1,1]]1
  • [[0,1],[1,0]]2
  • [[0,0,0],[0,0,1],[1,1,0]]2

Constraints#

  • 1 <= m, n <= 300, matrix[i][j] is 0 or 1.

Approach#

Two rows can be made equal by some flip set iff they are equal or exact bitwise complements. Canonicalize each row to “always starts with 0” (flip the row if it starts with 1), hash-count canonical forms, and return the most frequent.

Solution#

Flip Columns For Maximum Number of Equal Rows
class Solution {
public:
int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
unordered_map<string, int> freq;
int n = matrix[0].size();
for (auto& row : matrix) {
string key(n, '0');
int leader = row[0];
for (int j = 0; j < n; ++j) key[j] = ('0' + (row[j] ^ leader));
++freq[key];
}
int best = 0;
for (auto& [_, c] : freq) best = max(best, c);
return best;
}
};

Editorial#

The XOR canonicalization picks a single representative per equivalence class. Any column-flip choice that makes one row all-zero would equally make every row in its class all-zero — so the largest class is the answer.

Complexity#

  • Time: O(m*n).
  • Space: O(m*n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.