1007. Minimum Domino Rotations For Equal Row

Medium


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.

Example 1:

Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation: 
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.

Example 2:

Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation: 
In this case, it is not possible to rotate the dominoes to make one row of values equal.

Constraints:

  • 2 <= tops.length <= 2 * 104

  • bottoms.length == tops.length

  • 1 <= tops[i], bottoms[i] <= 6

class Solution:
    def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
        total = len(tops)
        sorted_top_counter, top_counter = self.get_best(tops)
        sorted_bottom_counter, bottom_counter = self.get_best(bottoms)
        
        top_diff = float("inf")
        for key, count in sorted_top_counter:
            if total - count < top_diff and (count + bottom_counter[key] >= total) and self.valid(tops, bottoms, key):
                top_diff = total - count
                
        for key, count in sorted_bottom_counter:
            if total - count < top_diff and (count + top_counter[key] >= total) and self.valid(tops, bottoms, key):
                top_diff = total - count
        minimum = top_diff
        return -1 if minimum == float("inf") else minimum
            
    # Check if there exists position for a key in either top or bottom row
    def valid(self, tops, bottoms, key):
        for index in range(len(tops)):
            if key != tops[index] and key != bottoms[index]:
                return False
        return True
        
    # Return counter of keys
    def get_best(self, tops: List[int]):
        top_counter = Counter()
        for top in tops:
            top_counter[top] += 1
        return top_counter.most_common(), top_counter

Solution 2 Taken from Leetcode

class Solution:
    def minDominoRotations(self, A: List[int], B: List[int]) -> int:
        same, countA, countB = Counter(), Counter(A), Counter(B)
        for a, b in zip(A, B):
            if a == b:
                same[a] += 1
        for i in range(1, 7):
            if countA[i] + countB[i] - same[i] == len(A):
                # countA-same or countB-same since `same` is common here take min of two counts
                return min(countA[i], countB[i]) - same[i]        
        return -1

Last updated