Ctrl K

Mirror Rows or Columns

Medium
You get a matrix grid of zeros and ones. A row or column is a mirror line if it reads the same in both directions. One flip changes any single cell to the opposite value. Return the minimum number of flips after which **either every row** or **every column** is a mirror line.
Example 1
grid=[[1, 1, 0], [0, 0, 1], [1, 0, 1]] → 2

Making every row a palindrome takes 2 flips (in the first two rows); the columns would also need 2, so the answer is 2.

Example 2
grid=[[0, 1, 1, 0], [1, 1, 0, 0]] → 2

Rows need 2 flips (the second row), columns need 2 too (two columns differ top and bottom). The minimum is 2.

Example 3
grid=[[1], [0], [0]] → 0

Each one-cell row already reads the same both ways.

Constraints
  • 1 ≤ len(grid) · len(grid[0]) ≤ 2 · 10⁵
  • All rows have the same length
  • grid[i][j] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMatch-Three Cascade MediumTipped Crate of Stones MediumMirrored Board in Fours MediumMirror and Negate a Bitmap EasyHow Far the Water Spreads Hard
loading Python…
Input
grid=[[1, 1, 0], [0, 0, 1], [1, 0, 1]]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.