Minimum Domino Rotations For Equal Row - Problem

In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the i-th domino. A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.

We may rotate the i-th 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.

Input & Output

Example 1 — Basic Case
$ Input: tops = [2,1,2,1], bottoms = [1,2,1,2]
Output: 2
💡 Note: We can make all tops equal to 2 by rotating dominoes at indices 1 and 3. After rotation: tops = [2,2,2,2]. Total rotations needed: 2.
Example 2 — Impossible Case
$ Input: tops = [3,5,1,2], bottoms = [3,6,3,3]
Output: -1
💡 Note: No single value appears in every domino position (tops[i] or bottoms[i]), so it's impossible to make all tops or all bottoms uniform.
Example 3 — No Rotations Needed
$ Input: tops = [1,1,1], bottoms = [2,2,2]
Output: 0
💡 Note: The tops are already all equal to 1, so no rotations are needed. Answer is 0.

Constraints

  • 2 ≤ tops.length == bottoms.length ≤ 2 × 104
  • 1 ≤ tops[i], bottoms[i] ≤ 6

Visualization

Tap to expand
Minimum Domino Rotations For Equal Row INPUT Dominoes Arrangement: 2 1 1 2 2 1 1 2 Index: 0 1 2 3 tops[]: 2 1 2 1 bottoms[]: 1 2 1 2 Goal: Make all tops OR all bottoms same value First domino: top=2, bottom=1 Only check values 1 and 2 ALGORITHM STEPS 1 Check First Domino Candidates: tops[0]=2, bottoms[0]=1 2 Try Target = 2 Count rotations for all tops=2 i=0: top=2 (OK) i=1: top=1, bot=2 (rotate) i=2: top=2 (OK) i=3: top=1, bot=2 (rotate) top_rot=2 bot_rot=2 3 Try Target = 1 Count rotations for all tops=1 i=0: top=2, bot=1 (rotate) i=1: top=1 (OK) i=2: top=2, bot=1 (rotate) i=3: top=1 (OK) top_rot=2 bot_rot=2 4 Return Minimum min(2, 2, 2, 2) = 2 FINAL RESULT After 2 rotations (target=2 on top): 2 1 2 1 rotated 2 1 2 1 rotated tops[] after: 2 2 2 2 OK OUTPUT 2 Minimum rotations needed to make all tops equal to 2 Key Insight: If a solution exists, the target value MUST appear in the first domino (either top or bottom). This optimization reduces checks from 6 possible values to just 2 candidates from the first domino. Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Minimum Domino Rotations For Equal Row | Optimized - Check First Domino Only
Asked in
Amazon 15 Facebook 12 Google 8
18.5K Views
Medium Frequency
~15 min Avg. Time
892 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