Input: nums =[3,12,30,17,21]Output: 2Explanation:
The almost equal pairs of elements are:*3 and 30. By swapping 3 and 0in30, you get 3.*12 and 21. By swapping 1 and 2in12, you get 21.
For two numbers to be almost equal, one should be able to reach the other by swapping any two digits in one of them. For each number, we can generate all possible numbers by swapping any two digits (including itself), and count how many times each number appears. For each pair, if their swapped forms match, they are almost equal.
classSolution {
public:int countAlmostEqualPairs(vector<int>& nums) {
unordered_map<int, int> freq;
for (int x : nums) freq[x]++;
int ans =0;
for (int i =0; i < nums.size(); ++i) {
string s = to_string(nums[i]);
set<int> seen;
for (int a =0; a < s.size(); ++a) {
for (int b = a; b < s.size(); ++b) {
swap(s[a], s[b]);
int v = stoi(s);
if (!seen.count(v)) {
ans += freq[v] - (v == nums[i]);
seen.insert(v);
}
swap(s[a], s[b]);
}
}
}
return ans /2;
}
};
classSolution {
funcountAlmostEqualPairs(nums: IntArray): Int {
val freq = mutableMapOf<Int, Int>()
for (x in nums) freq[x] = freq.getOrDefault(x, 0) + 1var ans = 0for (i in nums.indices) {
val s = nums[i].toString().toCharArray()
val seen = mutableSetOf<Int>()
for (a in s.indices) {
for (b in a until s.size) {
s[a] = s[b].also { s[b] = s[a] }
val v = String(s).toInt()
if (v !in seen) {
ans += freq.getOrDefault(v, 0) - if (v == nums[i]) 1else0 seen.add(v)
}
s[a] = s[b].also { s[b] = s[a] }
}
}
}
return ans / 2 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defcountAlmostEqualPairs(self, nums: list[int]) -> int:
from collections import Counter
freq = Counter(nums)
ans =0for i, x in enumerate(nums):
s = list(str(x))
seen = set()
for a in range(len(s)):
for b in range(a, len(s)):
s[a], s[b] = s[b], s[a]
v = int(''.join(s))
if v notin seen:
ans += freq[v] - (v == x)
seen.add(v)
s[a], s[b] = s[b], s[a]
return ans //2
⏰ Time complexity: O(n * d^2), where n is the length of nums and d is the maximum number of digits in any number. For each number, we try all digit swaps.
🧺 Space complexity: O(n), for the frequency map and sets.