Problem
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 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
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
2 <= tops.length <= 2 * 104
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6
Solution
The goal is to find the minimum number of rotations required to make all values in the tops
array the same, or all values in the bottoms
array the same. Domino rotations involve swapping the values at a specific index between tops
and bottoms
.
Method 1 - Greedy
Approach:
- Identify Potential Candidates:
- For a uniform row, the candidate value must come from either the first domino’s
tops[0]
orbottoms[0]
. These two values are the only possible candidates for rotation.
- For a uniform row, the candidate value must come from either the first domino’s
- Count Rotations Needed:
- Evaluate the rotation separately for the candidate value
tops[0]
:- Count how many rotations are needed to make either all
tops
entries equal to this value or allbottoms
entries equal to this value.
- Count how many rotations are needed to make either all
- Repeat the above process for the candidate value
bottoms[0]
.
- Evaluate the rotation separately for the candidate value
- Check Validity:
- If either candidate value cannot achieve uniformity in either
tops
orbottoms
across the entire row, return-1
.
- If either candidate value cannot achieve uniformity in either
Reasoning:
- The choice of candidates is limited to
tops[0]
orbottoms[0]
because these values must appear in alltops
or allbottoms
for a row to be uniform after rotations. - Measure rotations for both candidates and return the minimum count required.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. As we iterate through the arrays once for each candidate, processing every domino in linear time. - 🧺 Space complexity:
O(1)
. Only a constant amount of space is used for counters and comparisons.