[LeetCode] Count Number of Bad Pairs

2364. Count Number of Bad Pairs

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
long long countBadPairs(vector<int>& nums) {
long long res = 0;
unordered_map<int, int> freq;
for(int i = 0; i < nums.size(); i++) {
res += i - freq[nums[i] - i];
freq[nums[i] - i]++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/07/PS/LeetCode/count-number-of-bad-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.