From ee63a4cb641ec693aea0f6dec0a90c386aa78024 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Wed, 22 Nov 2023 00:11:57 +0530 Subject: [PATCH] Create 1814. Count Nice Pairs in an Array --- 1814. Count Nice Pairs in an Array | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 1814. Count Nice Pairs in an Array diff --git a/1814. Count Nice Pairs in an Array b/1814. Count Nice Pairs in an Array new file mode 100644 index 0000000..a2d4d0d --- /dev/null +++ b/1814. Count Nice Pairs in an Array @@ -0,0 +1,27 @@ +class Solution { +public: + // time/space: O(nlogk)/O(n) + int countNicePairs(vector& nums) { + // count the difference for each number with its reverse + unordered_map 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; + } +};