#3239
Medium Algorithms Minimum number of flips to make binary grid palindromic i
Array Two Pointers Matrix
74.8% acceptance
Feb 25, 2026
81
10
You are given an m x n binary matrix grid.
A row or column is considered palindromic if its values read the same forward and backward.
You can flip any number of cells in grid from 0 to 1, or from 1 to 0.
Return the minimum number of cells that need to be flipped to make either all rows palindromic
or all columns palindromic.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn min_flips(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
// Flips to make all rows palindromic
let mut row_flips = 0i32;
for r in 0..m {
for c in 0..n / 2 {
if grid[r][c] != grid[r][n - 1 - c] {
row_flips += 1;
}
}
}
// Flips to make all columns palindromic
let mut col_flips = 0i32;
for c in 0..n {
for r in 0..m / 2 {
if grid[r][c] != grid[m - 1 - r][c] {
col_flips += 1;
}
}
}
row_flips.min(col_flips)
}
}