Difficulty: Medium
Given a 0-indexed integer array nums
, we define a pair of indices (i, j)
as a misaligned pair if:
Your task is to determine the total number of misaligned (or "bad") pairs in the array.
nums = [3, 3, 3]
3
Thus, there are 3 bad pairs in total.
nums = [5, 6, 7, 8]
0
Hence, there are no bad pairs.
Therefore, no pairs are misaligned.
https://leetcode.com/problems/count-number-of-bad-pairs/description
Loading component...
Loading component...
Main Function is not defined.
INPUT: nums = [1, 2, 3, 4, 5]
Output: 0
public long countBadPairs(int[] nums) {
int n = nums.length;
long totalPairs = (long) n * (n - 1) / 2;
Map<Long, Long> freq = new HashMap<>();
for (int i = 0; i < n; i++) {
long key = i - (long) nums[i];
freq.put(key, freq.getOrDefault(key, 0L) + 1);
}//Loop End
long goodPairs = 0;
for (long count : freq.values()) {
goodPairs += count * (count - 1) / 2;
}//Loop End
return totalPairs - goodPairs;
}//function end
Utility Function is not required.