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 = 1e9 + 7;
    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) {
      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
27
28
class Solution {
  public int countNicePairs(int[] nums) {
    final int kMod = (int) 1e9 + 7;
    long ans = 0;
    Map<Integer, Long> count = new HashMap<>();

    for (final int num : nums) {
      final int key = num - rev(num);
      count.put(key, count.getOrDefault(key, 0L) + 1);
    }

    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 = Counter(num - int(str(num)[::-1]) for num in nums)
    return sum(freq * (freq - 1) // 2 for freq in freqs.values()) % 1000000007
Back to top