Created
May 3, 2025 17:43
-
-
Save tatsuyax25/dd17e930c375a90373e74adb18bd93a3 to your computer and use it in GitHub Desktop.
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that tops[i] and bottoms[i] swap v
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finds the most frequently occurring number in an array. | |
* @param {number[]} arr - The input array of numbers. | |
* @return {Object} An object containing the most common item and its count. | |
*/ | |
function getMostFrequentNumber(arr = []) { | |
let mostFrequent = arr[0]; | |
let frequencyMap = {}; | |
for (let num of arr) { | |
frequencyMap[num] = (frequencyMap[num] || 0) + 1; | |
if (frequencyMap[mostFrequent] < frequencyMap[num]) { | |
mostFrequent = num; | |
} | |
} | |
return { | |
item: mostFrequent, | |
occurrences: frequencyMap[mostFrequent] | |
}; | |
} | |
var minDominoRotations = function (tops, bottoms) { | |
// Find the most frequent values in each row | |
const { item: mostFrequentTop, occurrences: countTop } = getMostFrequentNumber(tops); | |
const { item: mostFrequentBottom, occurrences: countBottom } = getMostFrequentNumber(bottoms); | |
// Choose the value that appears most frequently across both arrays | |
const targetValue = countTop > countBottom ? mostFrequentTop : mostFrequentBottom; | |
const primaryArray = countTop > countBottom ? tops : bottoms; | |
const alternateArray = countTop <= countBottom ? tops : bottoms; | |
let rotationCount = 0, n = primaryArray.length; | |
// Check whether we can make all values equal to `targetValue` | |
for (let i = 0; i < n; i++) { | |
if (primaryArray[i] !== targetValue) { | |
// If neither the primary nor alternate array contains the target value at this index, it's impossible | |
if (alternateArray[i] !== targetValue) { | |
return -1; | |
} else { | |
// Otherwise, we need to rotate this domino | |
rotationCount++; | |
} | |
} | |
} | |
return rotationCount; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment