Minimum flips to make every row and column a palindrome
I was asked this
No reports yet. Sign in to say where you were asked it.
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
Mand contains onlyBandW
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.
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.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
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.
Sign in to submit your code; every attempt is kept here.
