Skip to content

Commit

Permalink
Create 1814. Count Nice Pairs in an Array (#349)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Nov 21, 2023
2 parents a33f510 + ee63a4c commit 8afa317
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 1814. Count Nice Pairs in an Array
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
public:
// time/space: O(nlogk)/O(n)
int countNicePairs(vector<int>& nums) {
// count the difference for each number with its reverse
unordered_map<int, int> hash;
for (auto& num : nums) hash[num - rev(num)]++;

// count the nice pairs
int count = 0;
for (auto& [key, value] : hash) {
long long pairs = ((1LL * value * (value - 1)) / 2LL) % MOD;
count = (count + pairs) % MOD;
}
return count;
}
private:
const int MOD = 1e9 + 7;
int rev(int x) {
int result = 0;
while (x > 0) {
result = 10 * result + (x % 10);
x /= 10;
}
return result;
}
};

0 comments on commit 8afa317

Please sign in to comment.