Simple and easy to understand | T.C. - O(n) | S.C. - O(1) | Java
The basic idea is that if either of the top[0] or bottom[0] is present in every set of top and bottom dominoes, then there can be a possibility of making any of
The basic idea is that if either of the top[0] or bottom[0] is present in every set of top and bottom dominoes, then there can be a possibility of making any of top/bottom row same with minimum number of swaps.\nFor example - \n```\ntop = {2,1,2,4,2,2}\nbottom = {5,2,6,2,3,2}\n```\nHere, `top[0] = 2` and `bottom[0] = 5`. That means only 2 or 5 can contest for same top/bottom and `{1,3,4,6}` are eliminated in the start itself.\nThen, we check if 2 or 5 is present in other set of `top[i]` and `bottom[i]` and if any one of them is not present in the `top[i]` and `bottom[i]` set, then that number is also eliminated. If both the numbers get eliminated, then we return -1. \nIf any of the numbers are not eliminated yet, then we check number of swaps required to get that number to the top and number of swaps required to get that number to the bottom. We return the minimum of both the answers.\nAlso, if both the numbers are not eliminated, then it means that top and bottom contain combination of those two numbers. Selecting any one of those numbers and trying to make it in the top/bottom will automatically manage the second number.\n```\npublic int minDominoRotations(int[] top, int[] bottom) {\n        int n = top.length;\n        int a = top[0], b = bottom[0];\n        for(int i = 1 ; i < n ; i++) {\n            if(a != top[i] && a != bottom[i])\n                a = -1;\n            if(b != top[i] && b != bottom[i])\n                b = -1;\n            if(a == -1 && b == -1)\n                return -1;\n        }\n        \n        a = a != -1 ? a : b;\n        int tswap = 0, bswap = 0;\n        for(int i = 0 ; i < n ; i++) {\n            if(a != top[i])\n                tswap++;\n            \n            if(a != bottom[i])\n                bswap++;\n        }\n        return Math.min(tswap, bswap);\n    }\n```
['Java']