LeetCode 1814: Count Nice Pairs in an Array
Problem Description
Explanation
To solve this problem, we can iterate through the array and for each element, calculate its value plus the reverse of its value. We can store these values in a hashmap and for each new calculated value, we can check how many times it has occurred before. This count helps in calculating the number of nice pairs.
Algorithmic Idea
- Iterate through the array and for each element, calculate its value plus the reverse of its value.
- Store these calculated values in a hashmap and keep track of the count of each value.
- For each new calculated value, check how many times it has occurred before and update the count of nice pairs accordingly.
- Return the total count of nice pairs modulo 10^9 + 7.
Time Complexity
The time complexity of this solution is O(n) where n is the length of the input array.
Space Complexity
The space complexity of this solution is O(n) where n is the length of the input array.
Solutions
class Solution {
public int countNicePairs(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
int nicePairs = 0;
for (int num : nums) {
int rev = reverse(num);
int diff = num - rev;
countMap.put(diff, countMap.getOrDefault(diff, 0) + 1);
nicePairs = (nicePairs + countMap.get(diff) - 1) % 1000000007;
}
return nicePairs;
}
private int reverse(int num) {
int rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
}
Loading editor...