Minimum Number of Flips to Make Binary Grid Palindromic II - 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 all rows and columns palindromic, and the total number of 1's in grid divisible by 4.

Input & Output

Example 1 — Basic 2x2 Grid
$ Input: grid = [[1,0],[0,1]]
Output: 2
💡 Note: Grid is already palindromic but has 2 ones. Need 2 more ones for divisibility by 4, so flip both 0s to 1s.
Example 2 — Single Row
$ Input: grid = [[1,0,0,1]]
Output: 0
💡 Note: Row [1,0,0,1] is palindromic, column palindromes are trivial (single element), and 2 ones is not divisible by 4. But since columns are trivial, we need 2 more 1s, making total 4, requiring 2 flips. Actually, need to recalculate - this would need 2 flips to make 4 ones total.
Example 3 — All Zeros
$ Input: grid = [[0,0],[0,0]]
Output: 0
💡 Note: Already palindromic and 0 ones is divisible by 4, so no flips needed.

Constraints

  • 1 ≤ m, n ≤ 1000
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
INPUT GRIDALGORITHMRESULT1001Binary MatrixCurrent 1s: 22 mod 4 = 2 ≠ 01Find Groups2Count Values3Choose Majority4Adjust DivisionGroup 1: (0,0)↔(1,1)Group 2: (0,1)↔(1,0)Both groups keep valuesNeed 2 more 1s for ÷4Minimum Flips2Final 1s: 4All rows palindromic ✓All columns palindromic ✓Total 1s divisible by 4 ✓Optimal Solution!Key Insight:Group symmetric positions together - cells that must be equal for palindromes can be optimized as units, then adjust total count for divisibility constraint.TutorialsPoint - Minimum Number of Flips to Make Binary Grid Palindromic II | Optimized Grouping Approach
Asked in
Google 12 Microsoft 8 Amazon 6
8.9K Views
Medium Frequency
~25 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