[LeetCode] Count Nice Pairs in an Array

1814. Count Nice Pairs in an Array

You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:

  • 0 <= i < j < nums.length
  • nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])

Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
int reverse(int n) {
int res = 0;
while(n) {
res = res * 10 + n % 10;
n /= 10;
}
return res;
}
public:
int countNicePairs(vector<int>& nums) {
long long res = 0, mod = 1e9 + 7;
string rev;
unordered_map<int, int> m;
for(auto& n : nums) {
m[n - reverse(n)]++;
}
for(auto& [k, v] : m) {
res = (res + (v * (v-1) / 2 % mod)) % mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/10/PS/LeetCode/count-nice-pairs-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.