Fewest flips to make a domino row match: only the first domino's two values can work, so try each and keep the cheaper side.
▼The problem
LeetCode 1007 (Medium). tops[i] and bottoms[i] are the top and bottom halves of domino i (values 1 to 6). A rotation swaps the two halves of one domino. Return the minimum number of rotations that makes every value in tops equal, or every value in bottoms equal; if it cannot be done, return -1.
Examples (LeetCode's): tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2] → 2 (rotate dominoes 1 and 3: every top is 2) and tops = [3,5,1,2,3], bottoms = [3,6,3,3,4] → -1 (no value is on every domino: 1, 2, 4, 5 and 6 are missing from domino 0, 3 from domino 1).
The solution
def min_domino_rotations(tops, bottoms):
def cost(x):
top = bottom = 0
for a, b in zip(tops, bottoms):
if a != x and b != x:
return float('inf')
if a != x: top += 1
if b != x: bottom += 1
return min(top, bottom)
best = min(cost(tops[0]), cost(bottoms[0]))
return -1 if best == float('inf') else bestTranscript
Minimum Domino Rotations for Equal Row. Each domino has a top and a bottom number, and a rotation flips one, swapping its halves. Find the fewest rotations that make every top the same, or every bottom the same, or return minus one.
Here are six dominoes. The tops read two, one, two, four, two, two. Flip dominoes one and three, and every top is a two: two rotations. In this row, no number is on every domino: minus one.
The brute force tries every set of flips. Each domino flips or stays, so six dominoes give sixty-four sets: two to the n. Or try each face, one to six, for both rows: twelve passes, mostly hopeless.
Here's the key idea. The winning number must show on every domino, including domino zero. So only domino zero's two faces can win: here, two and five. Every other number is out before we start.
For each candidate, walk the row once. A domino with the candidate on neither half rules it out. Otherwise, count the tops that aren't the candidate, and the bottoms that aren't. Each count is the flips for that row. Keep the smaller.
Walking example one. For two: domino zero needs a bottom flip, one a top flip, two a bottom flip, three a top flip, four a bottom flip, and five shows two on both. Two top flips beat three bottom flips, so two costs two. For five, domino one has neither half: five is out. The answer is two.
In code, cost walks the pairs for one candidate. A domino without it returns infinity. Otherwise, it counts top and bottom flips, and returns the smaller. Try both faces of domino zero, and return the best, or minus one if both are infinite.
At most two passes over n dominoes: O of n time. And O of one space: just two counters.
Read domino zero, walk the row, keep the cheaper side. That's Minimum Domino Rotations.