Skip to content

1814. Count Nice Pairs in an Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
class Solution {
 public:
  int countNicePairs(vector<int>& nums) {
    constexpr int kMod = 1'000'000'007;
    long ans = 0;
    unordered_map<int, long> count;

    for (const int num : nums)
      ++count[num - rev(num)];

    for (const auto& [_, freq] : count) {
      ans += freq * (freq - 1) / 2;
      ans %= kMod;
    }

    return ans;
  }

 private:
  int rev(int n) {
    int x = 0;
    while (n > 0) {
      x = x * 10 + (n % 10);
      n /= 10;
    }
    return x;
  }
};
 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
class Solution {
  public int countNicePairs(int[] nums) {
    final int kMod = 1_000_000_007;
    long ans = 0;
    Map<Integer, Long> count = new HashMap<>();

    for (final int num : nums)
      count.merge(num - rev(num), 1L, Long::sum);

    for (final long freq : count.values()) {
      ans += freq * (freq - 1) / 2;
      ans %= kMod;
    }

    return (int) ans;
  }

  private int rev(int n) {
    int x = 0;
    while (n > 0) {
      x = x * 10 + (n % 10);
      n /= 10;
    }
    return x;
  }
}
1
2
3
4
class Solution:
  def countNicePairs(self, nums: list[int]) -> int:
    freqs = collections.Counter(num - int(str(num)[::-1]) for num in nums)
    return sum(freq * (freq - 1) // 2 for freq in freqs.values()) % 1000000007