Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A uniform row must use one of the first domino's two values, so there are at most two candidates. A candidate is possible only if every domino contains it on at least one side. Once feasible, the better target row is the one already containing more copies.
Approach
Try the first top value and then the first bottom value. For each, scan all dominoes and reject the candidate if neither side matches. Python counts matches on each row and returns n - max(topMatches, bottomMatches) for a feasible candidate. JavaScript counts mismatches, which are the required rotations, and returns the smaller count. Both return the first feasible candidate: if both distinct candidates work, every domino contains both, and they yield the same minimum. Return -1 if neither works.
class Solution:
def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
n = len(tops)
for x in [tops[0], bottoms[0]]:
b = 0
t = 0
next = False
for i in range(n):
if bottoms[i] != x and tops[i] != x:
if x == bottoms[0]: return -1
next = True
break
if bottoms[i] == x: b += 1
if tops[i] == x: t += 1
if next: continue
return n - max(b, t)
return -1Complexity analysis
Both displayed solutions test at most two candidate values and scan n dominoes for each. Time is O(n) and auxiliary space is O(1).
