Minimum Domino Rotations For Equal Row — LeetCode 1007 Python Solution

MediumGreedyArray
Problem
#1007
Pattern
Greedy
Reading time
3 min

The problem

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.

Example

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.

Python solution

Python
class Solution:
    def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
        def f(x: int) -> int:
            cnt1 = cnt2 = 0
            for a, b in zip(tops, bottoms):
                if x not in (a, b):
                    return inf
                cnt1 += a == x
                cnt2 += b == x
            return len(tops) - max(cnt1, cnt2)

        ans = min(f(tops[0]), f(bottoms[0]))
        return -1 if ans == inf else ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1007. Minimum Domino Rotations For Equal Row is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1007. Minimum Domino Rotations For Equal Row?
LeetCode 1007. Minimum Domino Rotations For Equal Row is rated Medium on LeetCode.
What is the time complexity of LeetCode 1007. Minimum Domino Rotations For Equal Row?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 1007. Minimum Domino Rotations For Equal Row?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1007. Minimum Domino Rotations For Equal Row cover?
LeetCode 1007. Minimum Domino Rotations For Equal Row is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview