304 North Cardinal St.
Dorchester Center, MA 02124

# Count Number of Bad Pairs LeetCode Solution

## Problem – Count Number of Bad Pairs LeetCode Solution

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`

### Count Number of Bad Pairs LeetCode Solution in C++

`````` long long countBadPairs(vector<int>& a,long cnt=0) {
unordered_map<int,int> mp;
for(int i=0;i<size(a);i++)
cnt+= i- mp[i-a[i]]++;
return cnt;
}
``````

### Count Number of Bad Pairs LeetCode Solution in Java

``````public long countBadPairs(int[] a) {
long cnt=0;
HashMap<Integer,Integer> mp= new HashMap<>();
for(int i=0;i<a.length;i++){
int prev= mp.getOrDefault(i-a[i],0);
cnt+= i- prev;
mp.put(i-a[i],prev+1);
}
return cnt;
}
``````

### Count Number of Bad Pairs LeetCode Solution in Python

``````class Solution:
def countBadPairs(self, nums: List[int]) -> int:
tot = len(nums) * (len(nums) - 1) // 2
good = 0
dp = {}

for i,num in enumerate(nums):
v = i - num
good += dp.get(v, 0)
dp[v] = dp.get(v, 0) + 1

``````
##### Count Number of Bad Pairs LeetCode Solution Review:

In our experience, we suggest you solve this Count Number of Bad Pairs LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Count Number of Bad Pairs LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Count Number of Bad Pairs LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions