Problem
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
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Counting Nice Pairs Using Differences and Hashing
- Conditions for a “Nice” Pair:
0 <= i < j < nums.length
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
- Key Insight:
- The condition
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
is equivalent tonums[i] - rev(nums[i]) == nums[j] - rev(nums[j])
.
- The condition
- Algorithm:
- Compute
diff[i] = nums[i] - rev(nums[i])
for eachi
. - Count the frequency of each value in
diff
. - The number of pairs with the same value of
diff
can be computed using combinatorial counting. Here is the approach:
- Compute
- Compute Reversed Digits: Implement a helper function
rev(x)
to reverse the digits of a number. - Compute Differences: For each number in
nums
, computediff[i] = nums[i] - rev(nums[i])
. - Count Pairs: Use a hash map to count the frequency of each unique value in
diff
. For each unique value with frequencyf
, the number of pairs isf * (f - 1) / 2
. - Modulo Operation: Since the result needs to be modulo (10^9 + 7), ensure all operations respect this constraint.
Code
|
|
|
|
Complexity
- Time:
O(n)
, where (n) is the length of the array. This is because each operation (reversing a number, calculating differences, and counting frequencies) is done in linear time. - Space:
O(n)
, due to the auxiliary space used by the hash map to store differences and their frequencies.