← Questions

Minimum flips to make every row and column a palindrome

0
MicrosoftCoding

You are given an N x M grid as a list of strings. Each cell is either "B" (black) or "W" (white).

A row is symmetric if it reads the same left to right as right to left. A column is symmetric if it reads the same top to bottom as bottom to top.

One flip changes a single cell from B to W or from W to B. Return the minimum number of flips needed so that every row and every column is symmetric.

def min_flips(grid: list[str]) -> int: ...

Constraints

  • 1 <= N, M <= 1000 (an empty grid returns 0)
  • every string has length M and contains only B and W

Example 1

grid = ["BW",
        "WB"]

Output: 2. All four cells must end up the same colour (each is the mirror of the others). Two are black and two are white, so two flips are needed.

Example 2

grid = ["BBWW",
        "WBBW",
        "BWWB"]

Output: 2. Flip (0,3) to B and (0,1) to W. The grid becomes BWWB / WBBW / BWWB, and every row and column is now a palindrome.

Be ready to explain why your answer is the minimum, and to return the resulting grid as well.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding