Flip Columns For Maximum Number of Equal Rows Problem
Description
LeetCode Problem 1072.
You are given an m x n binary matrix matrix.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).
Return the maximum number of rows that have all values equal after some number of flips.
Example 1:
Input: matrix = [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: matrix = [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
Input: matrix = [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300matrix[i][j]is either0or1.
Solution
Approach: Group Rows by Pattern
Take one set of column flips and look at two rows that both end up with all values equal. Either they end up the same (both all 0 or both all 1), and then they were equal to begin with, or they end up opposite, and then one was the exact complement of the other. So a set of flips can make a group of rows uniform only if every row in the group equals some pattern or its complement. And it always works for such a group: flip exactly the columns where the pattern has a 1.
To put a row and its complement into the same group, normalize each row so that it starts with 0: if row[0] is 1, flip the whole row (XOR every value with row[0]). [1,0,1] and [0,1,0] both become [0,1,0].
Count how often each normalized row appears in a hash map. The largest count is the answer.
Complexity: O(m · n) time to build and hash every key, where the matrix is m x n. O(m · n) space for the keys in the map.
from collections import Counter
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
cnt = Counter()
for row in matrix:
# Flip the row so it starts with 0: a row and its complement get the same key.
key = tuple(x ^ row[0] for x in row)
cnt[key] += 1
return max(cnt.values())