Leetcode #2174: Remove All Ones With Row and Column Flips II
In this guide, we solve Leetcode #2174 Remove All Ones With Row and Column Flips II 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 a 0-indexed m x n binary matrix grid. In one operation, you can choose any i and j that meet the following conditions: 0 <= i < m 0 <= j < n grid[i][j] == 1 and change the values of all cells in row i and column j to zero.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Bit Manipulation, Breadth-First Search, Array, Matrix
Intuition
We need level-by-level exploration or shortest steps, which is ideal for BFS.
A queue naturally models the frontier of the search.
Approach
Push initial nodes into a queue and expand in layers.
Track visited nodes to prevent cycles.
Steps:
- Initialize queue with start nodes.
- Process level by level.
- Track visited nodes.
Example
Input: grid = [[1,1,1],[1,1,1],[0,1,0]]
Output: 2
Explanation:
In the first operation, change all cell values of row 1 and column 1 to zero.
In the second operation, change all cell values of row 0 and column 0 to zero.
Python Solution
class Solution:
def removeOnes(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
state = sum(1 << (i * n + j) for i in range(m) for j in range(n) if grid[i][j])
q = deque([state])
vis = {state}
ans = 0
while q:
for _ in range(len(q)):
state = q.popleft()
if state == 0:
return ans
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
continue
nxt = state
for r in range(m):
nxt &= ~(1 << (r * n + j))
for c in range(n):
nxt &= ~(1 << (i * n + c))
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
ans += 1
return -1
Complexity
The time complexity is O(V+E). The space complexity is O(V).
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.