Minimum Domino Rotations For Equal Row Problem
Description
LeetCode Problem 1007.
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the i^th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i^th domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.
If it cannot be done, return -1.
Example 1:

Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Constraints:
2 <= tops.length <= 2 * 10^4bottoms.length == tops.length1 <= tops[i], bottoms[i] <= 6
Solution
Approach: Try the Two Values of the First Domino
If some row can be made all x, then every domino must show x on one of its halves, and in particular the first one. So x can only be tops[0] or bottoms[0], and we only need to try those two values.
For a candidate x, walk over the dominoes:
- If a domino has
xon neither half,xis impossible. - Otherwise count how many dominoes already show
xon top (inTop) and on the bottom (inBottom).
To make the top row all x, we rotate every domino that does not have x on top: n - inTop rotations. For the bottom row it is n - inBottom. We pick the row that already has more xs, so the cost is n - max(inTop, inBottom). (A domino with x on both halves counts in both, and never needs a rotation.)
The answer is the smaller cost of the two candidates, or -1 if both are impossible. We mark "impossible" as n + 1, which is larger than any real cost.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
n = len(tops)
def rotations(x: int) -> int:
"""Fewest rotations to make one row all x, or n + 1 if impossible."""
in_top = in_bottom = 0
for a, b in zip(tops, bottoms):
if a != x and b != x:
return n + 1 # this domino has no x at all
in_top += a == x
in_bottom += b == x
# Keep the row that already has more x's and rotate the others into it.
return n - max(in_top, in_bottom)
# The common value must appear on the first domino.
ans = min(rotations(tops[0]), rotations(bottoms[0]))
return -1 if ans > n else ans