Minimum flips to make every row and column a palindrome

0
Sign in

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.

MicrosoftCodingMedium

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.