[LeetCode] Count Almost Equal Pairs II

3267. Count Almost Equal Pairs II

Attention: In this version, the number of operations that can be performed, has been increased to twice.

You are given an array nums consisting of positive integers.

We call two integers x and y almost equal if both integers can become equal after performing the following operation at most twice:

  • Choose either x or y and swap any two digits within the chosen number.

Return the number of indices i and j in nums where i < j such that nums[i] and nums[j] are almost equal.

Note that it is allowed for an integer to have leading zeros after performing an operation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
bool ok(int x, int y) {
int a[4]{}, b[4]{}, p = 0;
while(x or y) {
if(x % 10 != y % 10) {
a[p] = x % 10;
b[p] = y % 10;
p++;
}
x /= 10;
y /= 10;
if(p == 4) break;
}
if(p <= 1) return p == 0;
if(x != y) return false;

if(p <= 3) {
sort(begin(a), end(a));
sort(begin(b), end(b));
return a[0] == b[0] and a[1] == b[1] and a[2] == b[2] and a[3] == b[3];
}
for(int i = 0; i < 3; i++) {
for(int j = i + 1; j < 4; j++) {
if(a[i] == b[j] and a[j] == b[i]) {
sort(begin(a), end(a));
sort(begin(b), end(b));
return a[0] == b[0] and a[1] == b[1] and a[2] == b[2] and a[3] == b[3];
}
}
}
return false;
}
public:
int countPairs(vector<int>& nums) {
int res = 0;
unordered_map<string, unordered_map<int,int>> freq;
for(int i = 0; i < nums.size(); i++) {
string s = to_string(nums[i]);
while(s.size() < 7) s.push_back('0');
sort(begin(s), end(s));
freq[s][nums[i]]++;
}
for(auto& [_,mp] : freq) {
for(auto it = begin(mp); it != end(mp); it++) {
res += it->second * (it->second - 1) / 2;
for(auto jt = next(it); jt != end(mp); jt++) {
if(ok(it->first, jt->first)) res += it->second * jt->second;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/25/PS/LeetCode/count-almost-equal-pairs-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.