1814. Count Nice Pairs in an Array
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 109 + 7.
Example: 1
Input: nums = [42,11,1,97]
Output: 2
Example: 2
Input: nums = [13,10,35,24,76]
Output: 4
Constraints:
- 1 <= nums.length <= 10 ^ 5
- 0 <= nums[i] <= 10 ^ 9
Step I (Changing the given equation a bit):
- The original equation is : nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]).
- So if we bring rev(nums[i]) to left and take rev(nums[j]) to the right, the equation will become : nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]).
- Here we can see that the sum of nums[i] - rev(nums[i]) must be equal to nums[j] - rev(nums[j]), for forming correct pairs.
Step II (Implementation):
- All we have to do now is to add up all nums[i] + rev(nums[i]) and store their count.
- Let's say there are N numbers having a particular sum Y. Then number of unique pairs will be : N * (N - 1) / 2.
- We will do this for all numbers formed by adding num and it's reverse, and then add the result together. This will be our final answer.
Full Code (Java):
class Solution {
public int countNicePairs(int[] nums) {
HashMap map = new HashMap<>();
for(int i : nums) {
long a = i;
long b = Long.parseLong(new StringBuilder("" + a).reverse().toString());
map.put(a - b, map.getOrDefault(a - b, 0) + 1);
}
long ans = 0;
for(long key : map.keySet()) {
long count = map.get(key);
ans += (count * (count - 1)) / 2L;
}
return (int)(ans % 1000_000_007L);
}
}
Comments
Post a Comment
If you have any queries or need solution for any problem, please let me know.