Magicsheet logo

Remove All Ones With Row and Column Flips II

Medium
25%
Updated 8/1/2025

Remove All Ones With Row and Column Flips II

What is this problem about?

The Remove All Ones With Row and Column Flips II interview question asks you to find the minimum number of operations to clear a binary matrix. In each operation, you select a cell containing a 1, and then set all cells in the same row and column as that cell to 0. Your goal is to reach an all-zero matrix using as few operations as possible. This problem sits at the intersection of matrix manipulation, bit manipulation, and state-space search using breadth-first search.

Why is this asked in interviews?

This problem is a favorite at Google because it blends multiple techniques: representing grid states as bitmasks, BFS to find the shortest path to the goal state, and understanding how row/column operations interact. It tests whether a candidate can reduce a 2D problem into an efficient 1D bit representation and reason about state transitions systematically rather than brute-forcing.

Algorithmic pattern used

The core pattern here is BFS on a bitmask state space combined with bit manipulation. Since the grid is small (up to 3x3 = 9 cells), the entire board can be encoded as a bitmask of at most 9 bits. Each BFS state is a unique integer. For each state, you enumerate every 1-bit (a cell that is set), apply the "flip row and column" operation, and transition to the resulting state. BFS guarantees you reach the zero-state in the minimum number of steps.

Example explanation

Imagine a 2x3 matrix:

1 0 0
0 1 0

Encoded as bits, this is 100010 (reading left to right, top to bottom). If you select cell (0,0), you zero out all of row 0 and column 0, leaving:

0 0 0
0 1 0

Now select cell (1,1), zeroing out row 1 and column 1:

0 0 0
0 0 0

Done in 2 operations. BFS would confirm 2 is the minimum.

Common mistakes candidates make

  • Forgetting to zero out both the entire row AND the entire column simultaneously — candidates sometimes only clear one direction.
  • Not encoding the state as a bitmask, leading to expensive matrix-copy operations and time limit issues.
  • Revisiting already-seen states, causing infinite BFS loops — always use a visited set.
  • Off-by-one errors when mapping 2D cell indices to bit positions.

Interview preparation tip

For the Remove All Ones With Row and Column Flips II coding problem, practice encoding small grids as integers before the interview. Write a helper that converts (row, col) to a bit index and another that applies a "row and column clear" operation on the bitmask. Once those building blocks are solid, the BFS layer is straightforward. Interviewers at Google appreciate when you explain your state encoding clearly before coding — it shows structured thinking.

Similar Questions