#3239

Minimum Number of Flips to Make Binary Grid Palindromic I

Medium
ArrayTwo PointersMatrixTwo PointersArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the symmetry of palindromes and uses a two-pointer technique to count the flips needed in a more efficient manner. This reduces the number of checks significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to count flips for rows and another for columns.
  2. 2Step 2: For each row, use two pointers to compare elements from the start and end, counting mismatches.
  3. 3Step 3: Repeat the same for columns using two pointers.
  4. 4Step 4: Return the minimum flips needed for either rows or columns.
solution.py26 lines
1# Full working Python code
2
3def minFlips(grid):
4    m, n = len(grid), len(grid[0])
5    row_flips = 0
6    col_flips = 0
7
8    # Check rows
9    for i in range(m):
10        left, right = 0, n - 1
11        while left < right:
12            if grid[i][left] != grid[i][right]:
13                row_flips += 1
14            left += 1
15            right -= 1
16
17    # Check columns
18    for j in range(n):
19        top, bottom = 0, m - 1
20        while top < bottom:
21            if grid[top][j] != grid[bottom][j]:
22                col_flips += 1
23            top += 1
24            bottom -= 1
25
26    return min(row_flips, col_flips)

Complexity note: The time complexity is O(n) because we only need to check each element once per row and column. The space complexity is O(1) since we use a constant amount of space for counting flips.

  • 1Flipping a cell affects both its row and column, so we need to consider both dimensions.
  • 2Using two pointers allows us to efficiently count mismatches without redundant checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.