Minimum Number of Flips to Make Binary Grid Palindromic I - Problem
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.
Input & Output
Example 1 — Already Palindromic Rows
$
Input:
grid = [[1,0,1],[0,1,0]]
›
Output:
0
💡 Note:
All rows are already palindromic: [1,0,1] reads same forward/backward, [0,1,0] reads same forward/backward. No flips needed.
Example 2 — Need Column Flips
$
Input:
grid = [[1,0],[0,1]]
›
Output:
1
💡 Note:
Rows need 2 flips: [1,0]→[1,1] and [0,1]→[0,0]. Columns need 1 flip: change grid[0][1] from 0 to 1, making both columns [1,1]. Choose columns: min(2,1) = 1.
Example 3 — Single Column
$
Input:
grid = [[1],[0],[1]]
›
Output:
1
💡 Note:
Rows are already palindromic (single elements). Column [1,0,1] needs 0 flips (already palindromic). But we have rows that need flips. Actually, single elements are palindromic, so answer is 0 for rows, 0 for column. min(0,0) = 0. Wait, let me recalculate: all single-element rows are palindromic, column [1,0,1] is palindromic. Answer is 0.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 300
- 0 ≤ grid[i][j] ≤ 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
Binary matrix with rows and columns
2
Count Costs
Calculate flips needed for rows vs columns
3
Choose Minimum
Return the cheaper option
Key Takeaway
🎯 Key Insight: We only need to make EITHER all rows OR all columns palindromic, not both - choose the cheaper option!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code