You are given a 0-indexed integer array nums
. A pair of indices (i, j)
is a bad pair if i < j
and j - i != nums[j] - nums[i]
.
Return the total number of bad pairs in nums
.
Count Number of Bad Pairs LeetCode Contest
Example 1:
Input: nums = [4,1,3,3] Output: 5 Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4. The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1. The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1. The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2. The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0. There are a total of 5 bad pairs, so we return 5.
Example 2:
Input: nums = [1,2,3,4,5] Output: 0 Explanation: There are no bad pairs.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
Solution
class Solution {
public long countBadPairs(int[] nums) {
HashMap<Integer, Integer> fMap = new HashMap<>();
int n = nums.length;
long N = 1L * (n-1);
long tp = (N*(N+1))/2;
long vp = 0;
for(int i = 0; i < n ; i++){
int val = nums[i] - i;
fMap.put(val, fMap.getOrDefault(val,0)+1);
}
for(int i = 0; i < n ; i++){
Integer key = nums[i] - i;
Integer value = fMap.get(key);
if(value >= 2){
vp += value-1;
fMap.put(key, value-1);
}
}
return tp-vp;
}
}
long long countBadPairs(vector<int>& nums) {
long long ans = 0;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); i++) {
ans += i - m[nums[i] - i];
m[nums[i] - i] += 1;
}
return ans;
}
def countBadPairs(self, A: List[int]) -> int:
m, ans = defaultdict(int), 0
for i in range(len(A)):
ans += i - m[A[i] - i]
m[A[i] - i] += 1
return ans
Happy Learning – If you require any further information, feel free to contact me.