Minimum Domino Rotations For Equal Row - Problem
Imagine you have a row of dominoes, where each domino has two numbers (from 1 to 6) - one on top and one on bottom. You can rotate any domino to swap its top and bottom values.
Given two arrays tops[] and bottoms[] representing the top and bottom halves of each domino, find the minimum number of rotations needed to make either:
- All values in the
topsarray the same, OR - All values in the
bottomsarray the same
If it's impossible to achieve either goal, return -1.
Example: If you have dominoes [2,1], [2,3], [1,3], you could rotate the third domino to get tops=[2,2,3] and bottoms=[1,3,1], then rotate the third again to get all 2s on top with just 1 rotation total.
Input & Output
basic_case.py โ Python
$
Input:
tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
โบ
Output:
2
๐ก Note:
We can make all values in tops equal to 2 with 2 rotations: rotate positions 1 and 4 to bring 2 from bottom to top.
impossible_case.py โ Python
$
Input:
tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
โบ
Output:
-1
๐ก Note:
No matter how we rotate, we cannot make all values in tops or bottoms the same. For example, position 1 has [5,6] and position 3 has [2,3], so they share no common value.
no_rotation_needed.py โ Python
$
Input:
tops = [1,1,1,1], bottoms = [2,2,2,2]
โบ
Output:
0
๐ก Note:
All values in tops are already the same (all 1s), so no rotations are needed.
Constraints
- 2 โค tops.length โค 2 ร 104
- bottoms.length == tops.length
- 1 โค tops[i], bottoms[i] โค 6
- Each domino has exactly two values (top and bottom)
Visualization
Tap to expand
Understanding the Visualization
1
Identify Possibilities
Only the values visible on the first card can possibly appear on all cards
2
Check Each Candidate
For each candidate, count how many cards need flipping to show that value
3
Choose Optimal
Pick the candidate requiring minimum flips, or return -1 if impossible
Key Takeaway
๐ฏ Key Insight: Only values present in the first domino can possibly work for the entire row, reducing our search space from exponential to constant time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code