Minimum Domino Rotations For Equal Row

Turn as few dominoes as possible so that the top row or the bottom row shows one number all the way along.

A row of dominoes is described by two arrays: tops[i] is the number on the top half of domino i, and bottoms[i] the number on its bottom half, each from 1 to 6. Dominoes are numbered from 0. A rotation turns one domino over, so its top and bottom numbers swap. Return the fewest rotations that make every top show the same number, or every bottom show the same number. If neither can be done, return -1.

Example 1
Input: tops = [2, 1, 2, 4, 2, 2], bottoms = [5, 2, 6, 2, 3, 2]
Output: 2
Explanation: rotate dominoes 1 and 3, and every top shows 2.
Example 2
Input: tops = [3, 5, 1, 2, 3], bottoms = [3, 6, 3, 3, 4]
Output: -1
Explanation: no number can fill the top row or the bottom row.
Solution

The Idea

Picture six dominoes standing side by side, each with one number on its upper half and one on its lower half. You may turn any domino upside down, which swaps its two numbers. The goal is a row where all the upper numbers match, or all the lower numbers match, after turning as few dominoes as you can.

In Example 1 the tops read 2, 1, 2, 4, 2, 2. Four of them already show 2. Domino 1 shows 1 on top and domino 3 shows 4, but both have a 2 underneath. Turning those two over makes the top row all 2s, so the answer is 2.

That was easy to spot by eye, but why 2? The halves can show any number from 1 to 6. Which numbers are even worth trying?

Look at domino 0. Whatever number ends up filling a row has to sit on every domino, so it has to sit on domino 0 too. Domino 0 shows 2 and 5, so those are the two numbers worth trying, and the other four can never work. Look at the picture below.

Example 1 tried with the two numbers on domino 0. Trying 2: every domino shows a 2, dominoes 1 and 3 need a rotation for the top row, so the top row needs 2 rotations and the bottom row 3. Trying 5: domino 1 has no 5, so the check stops there.

The row labelled "try 2" checks the top number of domino 0. Every domino has a 2 somewhere. The two marked "rotate" have it underneath, so the top row needs 2 rotations. Dominoes 0, 2 and 4 have their 2 on top, so the bottom row would need 3. The better of the two is 2.

The row labelled "try 5" checks the bottom number of domino 0. Domino 1 shows 1 and 2, with no 5, and no rotation can put a 5 there. So 5 cannot fill either row, and the dominoes after it are not checked. Example 2 fails the same way: domino 0 shows 3 on both halves, so 3 is the one number to try, and domino 1, showing 5 and 6, has no 3.

Once the number is fixed, each domino decides on its own. To fill the top row with 2, a domino is turned exactly when its top is not 2, whatever the other dominoes do. Settling each domino on the spot like this, with no looking ahead and no going back, is called a greedy choice, and here it gives the fewest rotations.

Solution Approach

Turning that idea into code means settling three things: which numbers to try, how to count the rotations for one number, and what to do when a domino lacks that number.

Which numbers to try

Why not try every way of turning the dominoes? Each domino is turned or not, so six dominoes give 26 = 64 ways, and 30 dominoes give over a billion. Fixing the number first removes that search, because each domino's choice then follows from its own two halves.

Trying all six numbers from 1 to 6 would also work, with six passes over the dominoes. Domino 0 cuts that to two: tops[0] and bottoms[0]. When both halves of domino 0 match, as in Example 2, the same number is simply tried twice.

Counting rotations for one number

How many turns does one number need? Keep two counts while walking along the dominoes. One counts dominoes whose top is not the number, since each of those must be turned to fill the top row. The other counts dominoes whose bottom is not the number, for the bottom row.

The answer for that number is the smaller count. Both rows matter: in Example 1 the top row needs 2 turns and the bottom row 3, but in another input the bottom row might already be full and need none.

A domino without the number

What if a domino shows the number on neither half? Then neither row can be filled with it, and walking further is wasted work. The count stops and reports that the number fails. If both numbers from domino 0 fail, the answer is -1.

Java Solution

The method minDominoRotations and its helper rotations work in these steps:

  1. First, minDominoRotations calls rotations twice, once with tops[0] and once with bottoms[0] as the number to try, named target.
  2. Inside rotations, two counters start at 0: toTop for turns that fill the top row, and toBottom for turns that fill the bottom row. A loop then moves i over the dominoes.
  3. If domino i shows target on neither half, rotations returns Integer.MAX_VALUE straight away. That value marks a number that cannot fill either row.
  4. Otherwise toTop goes up by 1 when the top is not target, and toBottom goes up by 1 when the bottom is not. After the loop, rotations returns the smaller counter.
  5. Back in minDominoRotations, best is the smaller of the two results. It is still Integer.MAX_VALUE only when both numbers failed, and then the method returns -1 instead.

The main method runs both examples, an input whose bottom row is already full, one where the top number of domino 0 fails but its bottom number works, and a single domino.

Java
public class MinimumDominoRotationsForEqualRow {

    public static int minDominoRotations(int[] tops, int[] bottoms) {
        // The common value must appear on the first domino, so only two candidates exist.
        int best = Math.min(rotations(tops[0], tops, bottoms),
                            rotations(bottoms[0], tops, bottoms));
        return best == Integer.MAX_VALUE ? -1 : best;
    }

    private static int rotations(int target, int[] tops, int[] bottoms) {
        int toTop = 0;    // rotations so every top shows target
        int toBottom = 0; // rotations so every bottom shows target
        for (int i = 0; i < tops.length; i++) {
            if (tops[i] != target && bottoms[i] != target) {
                return Integer.MAX_VALUE; // this domino has no target at all
            }
            if (tops[i] != target) {
                toTop++;
            }
            if (bottoms[i] != target) {
                toBottom++;
            }
        }
        return Math.min(toTop, toBottom);
    }

    public static void main(String[] args) {
        System.out.println(minDominoRotations(new int[] {2, 1, 2, 4, 2, 2},
                                              new int[] {5, 2, 6, 2, 3, 2}));
        System.out.println(minDominoRotations(new int[] {3, 5, 1, 2, 3},
                                              new int[] {3, 6, 3, 3, 4}));
        System.out.println(minDominoRotations(new int[] {1, 2, 1}, new int[] {2, 2, 2}));
        System.out.println(minDominoRotations(new int[] {3, 1, 1}, new int[] {1, 2, 3}));
        System.out.println(minDominoRotations(new int[] {4}, new int[] {6}));
    }
}

Running it prints:

Output
2
-1
0
1
0

Example 1 gives 2, the count from the row labelled "try 2", and Example 2 gives -1. The third line, 0, comes from tops = [1, 2, 1] and bottoms = [2, 2, 2]. The bottom row already shows 2 everywhere, so no domino needs turning. A version that counts only toTop returns 2 for this input, because it turns dominoes 0 and 2 to bring their 2s to the top.

The fourth line, 1, comes from tops = [3, 1, 1] and bottoms = [1, 2, 3]. Trying 3 stops at domino 1, which shows 1 and 2. Trying 1 works: turning domino 0 makes the tops read 1, 1, 1. The last line is a single domino, 4 over 6, where each row already holds one number, so it needs 0 rotations.

Complexity

The work is at most two walks along the dominoes, one for each number on domino 0.

  • Time: O(n), because each of the two numbers gets at most one pass over the n dominoes, and a pass can stop early at a domino without that number.
  • Space: O(1), because each pass keeps only the two counters toTop and toBottom and the index i, and neither array is copied.

Narrowing the possible answers to a few values before counting also helps in Majority Element.