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
.
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
class Solution:
def countBadPairs(self, nums: List[int]) -> int:
arr = [i - v for i, v in enumerate(nums)]
cnt = Counter(arr)
n = len(arr)
return sum(v * (n - v) for v in cnt.values()) >> 1
class Solution {
public long countBadPairs(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
nums[i] = i - nums[i];
}
Map<Integer, Integer> cnt = new HashMap<>();
for (int v : nums) {
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
}
long ans = 0;
for (int v : cnt.values()) {
ans += v * (n - v);
}
return ans >> 1;
}
}
class Solution {
public:
long long countBadPairs(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; ++i) nums[i] = i - nums[i];
unordered_map<int, int> cnt;
for (int v : nums) cnt[v]++;
long long ans = 0;
for (auto [_, v] : cnt) ans += 1ll * v * (n - v);
return ans >> 1;
}
};
func countBadPairs(nums []int) int64 {
n := len(nums)
for i := range nums {
nums[i] = i - nums[i]
}
cnt := map[int]int{}
for _, v := range nums {
cnt[v]++
}
ans := 0
for _, v := range cnt {
ans += v * (n - v)
}
ans >>= 1
return int64(ans)
}