Minimum Number of Flips to Make Binary Grid Palindromic II - Problem
Transform a Binary Grid into Perfect Palindromic Harmony

You are given an m ร— n binary matrix grid containing only 0s and 1s. Your mission is to transform this grid to satisfy two challenging conditions simultaneously:

๐Ÿ“š Palindromic Perfection: Every row and every column must read the same forwards and backwards (palindromic)
๐Ÿ”ข Divisibility Rule: The total count of 1s in the entire grid must be divisible by 4

You can flip any cell from 0 to 1 or from 1 to 0. Each flip counts as one operation.

Goal: Return the minimum number of flips needed to achieve both conditions.

Example:
[[1,0,0],[0,1,0],[0,0,1]] โ†’ Minimum flips needed to make all rows/columns palindromic AND total 1s divisible by 4.

Input & Output

example_1.py โ€” Small Grid
$ Input: grid = [[1,0,0],[0,1,0],[0,0,1]]
โ€บ Output: 3
๐Ÿ’ก Note: Need to make rows and columns palindromic AND total 1s divisible by 4. Current grid has 3 ones. To make palindromic: (0,0)=1 must equal (0,2)=0 and (2,0)=0 must equal (2,2)=1, etc. Optimal solution flips 3 cells to achieve both conditions.
example_2.py โ€” Symmetric Grid
$ Input: grid = [[0,1,0],[1,0,1],[0,1,0]]
โ€บ Output: 0
๐Ÿ’ก Note: This grid is already palindromic in all rows and columns: [0,1,0] reads same forwards/backwards, and column [0,1,0] also palindromic. Total 1s = 4, which is divisible by 4. No flips needed.
example_3.py โ€” Edge Case
$ Input: grid = [[1,1],[1,1]]
โ€บ Output: 0
๐Ÿ’ก Note: All rows [1,1] and columns [1,1] are already palindromic. Total 1s = 4, divisible by 4. Perfect as-is, 0 flips needed.

Constraints

  • 1 โ‰ค m, n โ‰ค 1000
  • grid[i][j] is either 0 or 1
  • m ร— n โ‰ค 106 (total cells limited)
  • Solution must satisfy both palindromic AND divisibility conditions
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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