Optimized brute-force
We count numbers using a hash map n.\n\nBut first, we generate valid permutatins (one or two swaps) for each number, and check if we have matches in the hash ma
We count numbers using a hash map `n`.\n\nBut first, we generate valid permutatins (one or two swaps) for each number, and check if we have matches in the hash map. Note that we also need to de-duplicate permutations to avoid double-counting.\n\nNow, we want to make it as fast as possible:\n> The runtime limit for C++, I believe, is 3,000 ms, and the solution below is AC with 300 ms runtime.\n- Avoid `int` to `string` conversions - we `swap` two digits in integer.\n- Use global `vis` array for de-duplication. We can use a trick to avoid re-initialization by storing the index `id` of the number being processed.\n- Check if the first swap resulted in a different number, and only do the second swap if it does. \n\n**C++**\n```cpp\nint vis[10000000], pw[] = {1, 10, 100, 1000, 10000, 100000, 1000000};\nint swap(int n, int i, int j) {\n    return n + n / pw[i] % 10 * (pw[j] - pw[i]) + n / pw[j] % 10 * (pw[i] - pw[j]); \n}\nclass Solution {\npublic:\nunordered_map<int, int> m;   \nint count(int n, int i) {\n    if (exchange(vis[n], i + 1) != i + 1)\n        if (auto it = m.find(n); it != end(m))\n            return it->second;\n    return 0;\n}\nint countPairs(vector<int>& nums) {\n    int res = 0;\n    for (int id = 0; id < nums.size(); ++id) {\n        for (int i = 0; i < 7; ++i)\n            for (int j = i; j < 7; ++j) {\n                int n1 = swap(nums[id], i, j);\n                res += count(n1, id);\n                if (n1 != nums[id])\n                    for (int k = i + 1; k < 7; ++k)\n                        for (int l = k + 1; l < 7; ++l)\n                            res += count(swap(n1, k, l), id);                \n            }\n        ++m[nums[id]];\n    }\n    return res;\n}\n};\n```
['C']