1007.js
/** ------------------------------------------------------------------------------
*
* 1007. Minimum Domino Rotations For Equal Row
* Topics: Array, Greedy
* https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/description/?envType=daily-question&envId=2025-05-03
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} tops
* @param {number[]} bottoms
* @return {number}
*/
var minDominoRotations = function (tops, bottoms) {
const minRot = (target) => {
let toTop = 0,
toBottom = 0
for (let i = 0; i < tops.length; i++) {
const x = tops[i],
y = bottoms[i]
if (x !== target && y !== target) {
return Infinity
}
if (x !== target) {
toTop++
} else if (y !== target) {
toBottom++
}
}
return Math.min(toTop, toBottom)
}
const ans = Math.min(minRot(tops[0]), minRot(bottoms[0]))
return ans === Infinity ? -1 : ans
}
console.log(minDominoRotations([2, 1, 2, 4, 2, 2], [5, 2, 6, 2, 3, 2]))