[Python] short O(n) solution, explained
Nothing very special about this problem: we just need to do, what is asked. Let us do it in two steps:\n1. Find out if we are able to rotate several dominoes to
Nothing very special about this problem: we just need to do, what is asked. Let us do it in two steps:\n1. 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`.\n2. 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, that `s` 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).\n\n**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.\n\n```\nclass Solution:\n    def minDominoRotations(self, A, B):\n        s, n = set([1,2,3,4,5,6]), len(A)\n        for i in range(n): s &= set([A[i], B[i]])\n        if not s: return -1\n        flips1 = sum(A[i] == list(s)[0] for i in range(n))\n        flips2 = sum(B[i] == list(s)[0] for i in range(n))\n        return min(n - flips1, n - flips2)  \n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
[]