Use Sets for Easily Solving It
Time & Space:\n\n\nIntution:\nThe questions essentially boils down weather their exists a common element b/w all the indices and where to keep that value that i
**Time & Space:**\n![image](https://assets.leetcode.com/users/images/aa0f9793-2bbf-405c-bff5-5cbf308bccc7_1647836359.417393.png)\n\n**Intution:**\nThe questions essentially boils down weather their exists a common element b/w all the indices and where to keep that value that is on the top array or the bottom one. Something like this can be easily implemented using sets in python. We just need to find the intersection b/w the current possible intersection set and a set of **{top[i], bottom[i]}**\n\n**Steps:**\n1. Basically maintain a set called inter and initialize it by the values with a set of 1st values of tops and bottom array.\n2. Now loop over all the indices and get the intersection b/w inter and a set of top and bottom values at that index.\n3. Now we can have 3 cases:\n\n**Case 1: `len(inter) == 0`:** No intersection found, so it is not possible to provide the asked arrangement\n**Case 2: `len(inter) == 1`:** Only one value found *(call it **target**)*. But now we have two options that are either to keep target on the top array or to keep target with bottom array. We can simply do it by counting the occurence of target in the tops and bottoms array. We use the array with maximum number of these occurences as it would lead to mininum number of swaps. \n**Case 3: `len(inter) == 2`:** Two values found. Eg Testcase: `top = [1,1,1,2,2]` & `bottom = [2,2,2,1,1]`. Simply count the number of occurence of any in either array *(call it **movements**)*. Return minimum of `movements` or `N - movements`\n**Code:**\n```\nclass Solution:\n    def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n        n = len(tops) \n        inter = {tops[0], bottoms[0]}\n        for i in range(n):\n            inter = inter.intersection({tops[i], bottoms[i]})\n\t\t# This gives us the finaly common values b/w all the indices. \n        if len(inter) == 0: # Case 1\n            return -1\n        elif len(inter) == 2: # Case 3\n            target = inter.pop()\n            m = tops.count(target)\n            return min(m, n-m)\n        else: # Case 2\n            for_tops = for_bottom = 0\n            target = inter.pop()\n            target_in_tops = tops.count(target)\n            target_in_bottoms = bottoms.count(target)\n            return n - max(target_in_tops, target_in_bottoms)\n```\n\n\n\n
['Python', 'Python3']