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: 2
💡 Note: Rows need 2 flips: [1,0]→[1,1] (1 flip) and [0,1]→[0,0] (1 flip). Columns need 2 flips: change grid[0][0] or grid[1][0] to make column 0 palindromic (1 flip), and change grid[0][1] or grid[1][1] to make column 1 palindromic (1 flip). Both approaches need 2 flips: min(2,2) = 2.
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
Minimum Flips for Palindromic Grid INPUT Binary Grid (2x3) 1 0 1 0 1 0 R0 R1 C0 C1 C2 Input Values: grid = [[1,0,1], [0,1,0]] Goal: Make rows OR cols palindromic with min flips ALGORITHM STEPS 1 Check Row Palindromes Compare grid[i][j] with grid[i][n-1-j] 2 Count Row Flips R0: 1-0-1 (palindrome) R1: 0-1-0 (palindrome) 3 Check Col Palindromes Compare grid[i][j] with grid[m-1-i][j] 4 Return Minimum min(rowFlips, colFlips) Calculation: Row flips needed: 0 R0: 1==1, 0 flips R1: 0==0, 0 flips Total row flips = 0 FINAL RESULT All Rows Are Palindromic! 1 0 1 OK 0 1 0 OK center Output: 0 No flips needed! Grid is already valid. (Both rows are palindromes) Key Insight: For a row to be palindromic, elements at positions j and (n-1-j) must be equal. Count mismatches for all rows and all columns separately. The answer is min(total_row_flips, total_col_flips). Time: O(m*n) | Space: O(1) - We only need to compare and count, no extra storage required. TutorialsPoint - Minimum Number of Flips to Make Binary Grid Palindromic I | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
8.4K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen