Super simple java O(N*d^4) solution and explain
Intuition\n Describe your first thoughts on how to solve this problem. \nThe contraints were very tight, so a simple O(N^2) implementation might not work (thoug
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe contraints were very tight, so a simple O(N^2) implementation might not work (though it had for this problem). To solve this we need to think of a way to avoid the comparision between each pair of numbers, for this we should notice whether any subproblems are repeating or not, here we figure out that if we precompute find all the two swap variations of all the numbers and count how many times those variations have occured in HashMap datastructure, then we can find the answer by running a single for loop on the given int[] nums, counting the number of times a number has appeared in the hashmap.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nAdd your time complexity here, e.g. $$O(n*d^4)$$\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n    int[] pow = new int[]{1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000};\n    public int countPairs(int[] nums) {\n        Map<Integer, Integer> variations = new HashMap<>();\n        int ans = 0;\n        for(int i = 0; i < nums.length; i++){\n            ans += variations.getOrDefault(nums[i], 0);\n            // generate all twoSwaps\n            Set<Integer> twoSwaps = new HashSet<>();\n            for(int oneSwap: genOneSwap(nums[i]))\n                twoSwaps.addAll(genOneSwap(oneSwap));\n            for(int twoSwap: twoSwaps)\n                variations.put(twoSwap, variations.getOrDefault(twoSwap, 0)+1);\n        }\n\n        return ans;\n    }\n\n    public Set<Integer> genOneSwap(int x){\n        Set<Integer> oneSwaps = new HashSet<>();\n        oneSwaps.add(x);\n        int digit = 7;\n        for(int i = 0; i < digit; i++){\n            for(int j = i+1; j < digit; j++){\n                int di = (x/pow[i])%10;\n                int dj = (x/pow[j])%10;\n\n                // swap\n                int varx = x - di*pow[i] + dj*pow[i] - dj*pow[j] + di*pow[j];\n                oneSwaps.add(varx);\n            }\n        }\n        return oneSwaps;\n    }\n}\n```
['Java']