← Questions

Minimum flips to make every row and column a palindrome

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests matrix, greedy and two pointers.

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.

Clarifying questions

  • Must every row and every column be a palindrome, not just one of the two? (Yes, both.)
  • Is there any other rule, such as a required number of black cells?
  • Do odd sizes leave a middle row, column or cell?
  • Should we return the final grid too?

What a strong answer covers

  • Groups each cell with its mirror images: (i, j), (i, M-1-j), (N-1-i, j) and (N-1-i, M-1-j). Every cell in a group must end up the same color.
  • Each group costs the smaller of its black count and its white count. Groups have 4 cells, or 2 on a middle row or column, or 1 at the center.
  • Visits each group once. That is O(N x M) time and O(1) extra memory.
  • Explains why the groups are independent, so adding their costs gives the minimum.
  • Tests both examples, a 1 x 1 grid, a single row, odd and even sizes, and a grid that is already symmetric.

Follow-ups

  • Return the final grid.
  • Only the rows, or only the columns, must be palindromes.
  • The number of black cells must be a multiple of 4.
  • Each cell has its own flip cost.

Where it's asked

What it tests

matrix · greedy · two pointers

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