2128. Remove All Ones With Row and Column Flips π
Description
You are given an m x n binary matrix grid.
In one operation, you can choose any row or column and flip each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Return true if it is possible to remove all 1's from grid using any number of operations or false otherwise.
Example 1:
Input: grid = [[0,1,0],[1,0,1],[0,1,0]] Output: true Explanation: One possible way to remove all 1's from grid is to: - Flip the middle row - Flip the middle column
Example 2:
Input: grid = [[1,1,0],[0,0,0],[0,0,0]] Output: false Explanation: It is impossible to remove all 1's from grid.
Example 3:
Input: grid = [[0]] Output: true Explanation: There are no 1's in grid.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is either0or1.
Solutions
Solution 1: Hash Table
We observe that if two rows in the matrix satisfy one of the following conditions, they can be made equal by flipping certain columns:
- The corresponding elements of the two rows are equal, i.e., if one row is \(1,0,0,1\), the other row is also \(1,0,0,1\);
- The corresponding elements of the two rows are opposite, i.e., if one row is \(1,0,0,1\), the other row is \(0,1,1,0\).
We call two rows that satisfy one of the above conditions "equivalent rows." The answer to the problem is the maximum number of equivalent rows in the matrix.
Therefore, we can traverse each row of the matrix and convert each row into an "equivalent row" that starts with \(0\). Specifically:
- If the first element of the current row is \(0\), keep the row unchanged;
- If the first element of the current row is \(1\), flip every element in the row, i.e., \(0\) becomes \(1\), \(1\) becomes \(0\). In other words, we flip rows starting with \(1\) into "equivalent rows" starting with \(0\).
In this way, we only need to use a hash table to count each converted row. If the hash table contains only one element at the end, it means we can remove all \(1\)s from the matrix by flipping rows or columns.
The time complexity is \(O(mn)\) and the space complexity is \(O(m)\), where \(m\) and \(n\) are the number of rows and columns in the matrix, respectively.
Related problem:
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |


