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 tops array the same, OR
  • All values in the bottoms array 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
Domino Rotation VisualizationOriginal Configuration:211222Strategy: Check candidate '2'21โœ“ No rotation12๐Ÿ”„ Rotate (1)22โœ“ No rotationResult for '2':1 rotation needed(Flip middle domino)Final Answer: 1 rotation
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
67.4K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen