Leetcode #2128: Remove All Ones With Row and Column Flips
In this guide, we solve Leetcode #2128 Remove All Ones With Row and Column Flips in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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).
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Bit Manipulation, Array, Math, Matrix
Intuition
The problem structure lets us track state with bitwise operations.
Bit operations are constant time and avoid extra memory.
Approach
Apply XOR/AND/OR and shifts to maintain the required invariant.
Aggregate the result in a single pass.
Steps:
- Identify a bitwise invariant.
- Combine values with bit operations.
- Return the aggregated result.
Example
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
Python Solution
class Solution:
def removeOnes(self, grid: List[List[int]]) -> bool:
s = set()
for row in grid:
t = tuple(row) if row[0] == grid[0][0] else tuple(x ^ 1 for x in row)
s.add(t)
return len(s) == 1
Complexity
The time complexity is and the space complexity is , where and are the number of rows and columns in the matrix, respectively. The space complexity is , where and are the number of rows and columns in the matrix, respectively.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.