#1814
Medium Algorithms Count nice pairs in an array
Array Hash Table Math Counting
48.4% acceptance
Feb 25, 2026
2041
92
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 10^9 + 7.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn count_nice_pairs(nums: Vec<i32>) -> i32 {
const MOD: i64 = 1_000_000_007;
fn rev(mut x: i32) -> i32 {
let mut r = 0i32;
while x > 0 {
r = r * 10 + x % 10;
x /= 10;
}
r
}
let mut freq: HashMap<i32, i64> = HashMap::new();
for &n in &nums {
*freq.entry(n - rev(n)).or_insert(0) += 1;
}
let mut result: i64 = 0;
for &c in freq.values() {
result = (result + c * (c - 1) / 2) % MOD;
}
result as i32
}
}