C++ | easy to understand
\tint minDominoRotations(vector& tops, vector& bottoms) {\n        \n        int n = tops.size();\n        bool top=true,bottom=true;\n        int  val1 = tops[
\tint minDominoRotations(vector<int>& tops, vector<int>& bottoms) {\n        \n        int n = tops.size();\n        bool top=true,bottom=true;\n        int  val1 = tops[0];\n        int val2 = bottoms[0];\n        for(int i=1;i<n;i++)\n        {\n           if(top) if(val1 != tops[i] && val1 != bottoms[i]) top = false;\n           if(bottom) if(val2 != tops[i] && val2 != bottoms[i]) bottom = false;\n           if(!top && !bottom) return -1; \n        }\n        int key = val1;\n        if(bottom)\n        {\n            for(int i=0;i<n;i++)\n            {\n                int temp = tops[i];\n                tops[i] = bottoms[i];\n                bottoms[i] = temp;\n            }\n            key = val2;\n        }\n        \n        int count1=0,count2=0,flip=0;\n        for(int i=0;i<n;i++)\n        {\n            if(tops[i]==key)count1++;\n            if(bottoms[i]==key)count2++;\n        }\n        \n        for(int i=0;i<n;i++)\n        {\n            if(count1 < count2)\n            {\n                if(tops[i]==key && bottoms[i]!=key) flip++;\n            }\n            else\n            {\n                if(tops[i]!=key && bottoms[i]==key) flip++;\n            }\n        }\n        return flip;\n    }\n\t};\n\ntake two(top and bottom) variables to check whether the top[0] and bottom[0] element exist at all positions or not\nif bottom exist in whole array then swap all positions of tops to bottoms so as to make code generic because the below implemented code works as if top element exists in the whole array. Count occurrences of the key in tops and bottoms , which ever have less occurrences, at most those occurrences we have to swap.\nThere might be a case where key exist in both top and bottom so there we don\'t need to swap hence these kind of elements get substracted from the occurrences.
[]