Sponsored
Sponsored
This approach is based on selecting a target number to either dominate the top or bottom row and counting the minimum rotations needed.
We first choose a target which could dominate the row: either tops[0]
or bottoms[0]
. Then we iterate over each domino, using an additional check to verify if that target can fully dominate a row. If we face a domino where neither side contains the target, it's not possible for that target to dominate the row.
Time Complexity: O(n), where n is the number of dominoes.
Space Complexity: O(1)
This JavaScript solution encapsulates the checking logic in a function and evaluates the rotations required for the initial values of tops
and bottoms
.
To solve the problem using this approach, we evaluate the elements with the most appearance that could be converted to make a row uniform. This involves utilizing frequency maps to identify potential candidates quickly and checking their feasibility.
Time Complexity: O(n), where n is the number of dominoes.
Space Complexity: O(1)
1var minDominoRotations = function(tops, bottoms) {
2 const candidates = [tops[0], bottoms[0]];
3 for (const val of candidates) {
4 let rotations_a = 0, rotations_b = 0;
5 for (let i = 0; i < tops.length; ++i) {
6 if (tops[i] !== val && bottoms[i] !== val) {
7 rotations_a = rotations_b = Number.MAX_SAFE_INTEGER;
8 break;
9 } else if (tops[i] !== val) rotations_a++;
10 else if (bottoms[i] !== val) rotations_b++;
11 }
12 const rotations = Math.min(rotations_a, rotations_b);
13 if (rotations !== Number.MAX_SAFE_INTEGER) return rotations;
14 }
15 return -1;
16};
This JavaScript solution explores both numbers from the first domino and seeks to make one of them dominate by counting necessary rotations and confirming possibility directly.
Solve with full IDE support and test cases