Skip to content

2128. Remove All Ones With Row and Column Flips

  • Time: $O(mn)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  bool removeOnes(vector<vector<int>>& grid) {
    const vector<int> revRow = getRevRow(grid[0]);
    return ranges::all_of(
        grid, [&](const auto& row) { return row == grid[0] || row == revRow; });
  }

 private:
  vector<int> getRevRow(vector<int>& row) {
    vector<int> revRow;
    for (const int a : row)
      revRow.push_back(a ^ 1);
    return revRow;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public boolean removeOnes(int[][] grid) {
    int[] revRow = getRevRow(grid[0]);
    return Arrays.stream(grid).allMatch(
        row -> Arrays.equals(row, grid[0]) || Arrays.equals(row, revRow));
  }

  private int[] getRevRow(int[] row) {
    int[] revRow = new int[row.length];
    for (int i = 0; i < row.length; ++i)
      revRow[i] = row[i] ^ 1;
    return revRow;
  }
}
1
2
3
4
class Solution:
  def removeOnes(self, grid: List[List[int]]) -> bool:
    revRow = [a ^ 1 for a in grid[0]]
    return all(row == grid[0] or row == revRow for row in grid)