Beginner Friendly Solution with detail Explanation || 100%beats
Intuition\n Describe your first thoughts on how to solve this problem. \nOne observation is that, if A[0] works, no need to check B[0].\nBecause if both A[0] an
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne observation is that, if `A[0]` works, no need to check `B[0]`.\nBecause if both `A[0]` and `B[0]` exist in all dominoes,\nwhen you swap `A[0]` in a whole row,\nyou will swap `B[0]` in a whole at the same time.\nThe result of trying `A[0]` and `B[0]` will be the same.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nCount the occurrence of all numbers in A and B,\nand also the number of domino with two same numbers.\n\nTry all possibilities from 1 to 6.\nIf we can make number i in a whole row,\nit should satisfy that `top[i] + bottom[i] - equal_cnt[i] = n`\n\nTake example of\n`A = [2,1,2,4,2,2]`\n`B = [5,2,6,2,3,2]`\n\n`top[2] = 4`, as `A[0] = A[2] = A[4] = A[5] = 2`\n`bottom[2] = 3`, as `B[1] = B[3] = B[5] = 2`\n`equal_cnt[2] = 1`, as `A[5] = B[5] = 2`\n\nWe have `top[2] + bottom[2] - equal_cnt[2] = 6,`\nso we can make 2 in a whole row.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    private int helper(int[] tops, int[] bottoms, int val) {\n        int top_res = 0, bottom_res = 0;\n        for (int i = 0; i < tops.length; i++) {\n            if (tops[i] != val && bottoms[i] != val) {\n                return -1;\n            } else if (tops[i] != val) {\n                top_res++;\n            } else if (bottoms[i] != val) {\n                bottom_res++;\n            }\n        }\n        return Math.min(top_res, bottom_res);\n    }\n\n\n\n    public int minDominoRotations(int[] tops, int[] bottoms) {\n        // Approach-1\n        // int[] top = new int[7];\n        // int[] bottom = new int[7];\n        // int[] equal_cnt = new int[7];\n        // for (int i = 0; i < tops.length; i++) {\n        //     top[tops[i]]++;\n        //     bottom[bottoms[i]]++;\n        //     if (tops[i] == bottoms[i])\n        //         equal_cnt[tops[i]]++;\n        // }\n\n        // for (int i = 1; i < 7; i++) {\n        //     if (top[i] + bottom[i] - equal_cnt[i] == tops.length) {\n        //         return tops.length - Math.max(top[i], bottom[i]);\n        //     }\n        // }\n        // return -1;\n\n\n\n\n        // Approach-2\n        int ans = -1;\n        for (int i = 1; i < 7; i++) {\n            int cur_ans = helper(tops, bottoms, i);\n\n            if (cur_ans != -1 && (ans == -1 || ans > cur_ans)) {\n                ans = cur_ans;\n            }\n        }\n        return ans;\n    }\n}\n```
['Array', 'Greedy', 'Java']