[
array
greedy
]
Leetcode 1007. Minimum Domino Rotations For Equal Row
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row
Nothing very special about this problem: we just need to do, what is asked. Let us do it in two steps:
- Find out if we are able to rotate several dominoes to get what we want. How we can do it? All we need to do is to evaluate intersections of all sets of values for each domino. If this set is empty, then answer is
-1
. - Now, let us look on the first element of
s
if it is not empty. Then we calculate two numbers: one if we want to rotate them such that upper line has equal numbers and another if we want to rotate if we want second line have equal numbers. Finally, we return minumum of these two numbers. (note, that it can happen also, thats
has two elements, it means, that all dominoes are equal, and when we make one of the rows equal, the second one will have equal numbers as well).
Complexity: time complexity is O(n)
, because we traverse our list only 2 times each. Note, that even though we traverse our lists twice, this algorithm is not 2 times slower than so-called one-pass traversals.
class Solution:
def minDominoRotations(self, A, B):
s, n = set([1,2,3,4,5,6]), len(A)
for i in range(n): s &= set([A[i], B[i]])
if not s: return -1
flips1 = sum(A[i] == list(s)[0] for i in range(n))
flips2 = sum(B[i] == list(s)[0] for i in range(n))
return min(n - flips1, n - flips2)
If you like the solution, you can upvote it on leetcode discussion section: Problem 1007