Description
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.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] is either 0 or 1.
Solution
Solved after help.
Assume the i-th
row is all 0s after flipping x
columns, then:
- If there are other rows that are also all 0s, then before flipping it must be the same as the current row.
- If there are other rows that are all 1s, then before flipping it must be totally different from the current row.
So the question transforms to: find the row that has most same rows and most totally different rows.
An intuitive way is to store all the values in one row in a map, and for every row, check if the value or the opposite value has appeared before. If did appear, then add the value. Otherwise create a new value 1
.
Time complexity:
o
(
m
∗
n
)
o(m*n)
o(m∗n),
o
(
n
)
o(n)
o(n) for creating the row key,
o
(
m
)
o(m)
o(m) for iterating all the rows.
Space complexity:
o
(
m
∗
n
)
o(m*n)
o(m∗n)
Code
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
row_cnt = {}
for each_row in matrix:
row_key = ''.join(map(str, each_row))
oppo_row_key = ''.join('1' if x == '0' else '0' for x in row_key)
if row_key in row_cnt:
row_cnt[row_key] += 1
elif oppo_row_key in row_cnt:
row_cnt[oppo_row_key] += 1
else:
row_cnt[row_key] = 1
return max(row_cnt.values())