Solution
IntuitionImproved code for existing solution.
Just generate all strings that can be made by swapping at most twice for each num.
Count map stores the count of a
# Intuition\nImproved code for existing solution. \nJust generate all strings that can be made by swapping at most twice for each num.\nCount map stores the count of a number.\nWe add the counts of each neighbour to total. Why?\nSo, at each step you are adding increasing the count of a num present in ""nums"" only and not the neighbour. You have to check if any neighbour of the current num is already seen previously.\nNeighbour is the string that you can get within 2 swaps.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$  \n- Space complexity:\n$$O(n)$$\n\n# Code\n```python3 []\n\nclass Solution:\n    def countPairs(self, nums: List[int]) -> int:\n        total = 0\n        count_map = Counter() # counts of neighbours of some like {"123545": 3}\n        \n        for num in nums:\n            num = str(num).zfill(7) # padd 0\'s to front make len 7, see constraints\n            neighbours = set([num]) \n            num_list = list(num)     # [1,2,3,5,4,5]\n            \n            for i in range(7):\n                for j in range(i):\n                    num_list[i], num_list[j] = num_list[j], num_list[i] # swap op 1\n                    neighbours.add("".join(num_list))\n                    \n                    for k in range(7):\n                        for l in range(k):\n                            num_list[k], num_list[l] = num_list[l], num_list[k]# swap op 2\n                            neighbours.add("".join(num_list))\n                            num_list[k], num_list[l] = num_list[l], num_list[k] # undo swap op 2\n                            \n                    num_list[i], num_list[j] = num_list[j], num_list[i] # undo swap op 1\n\n            for neighbour in neighbours:  # slighly complex to understand and come up with part in my opinion, maybe easy for others\n                total += count_map[neighbour]\n                \n            count_map[num] += 1\n        return total\n\n```
['Python3']