Problem Description
Given a 0-indexed integer array nums, a pair of indices (i, j) is called a bad pair if i < j and j - i != nums[j] - nums[i]. The task is to return the total number of bad pairs in nums.
Key Insights
- Instead of directly counting bad pairs, count the total number of pairs and subtract the number of good pairs.
- A good pair satisfies j - i == nums[j] - nums[i], which can be rearranged to nums[i] - i == nums[j] - j.
- Use a hash table to count the frequency of each value of (nums[i] - i).
- The number of good pairs for a particular key is c * (c - 1) / 2 if the frequency is c.
- Total pairs can be calculated using the formula n * (n - 1) / 2, where n is the length of the array.
Space and Time Complexity
Time Complexity: O(n) because we iterate through the array once and perform O(1) operations inside the loop. Space Complexity: O(n) in the worst-case scenario where all (nums[i] - i) values are unique, storing counts for each index.
Solution
The solution involves two main steps:
- Calculate the total number of index pairs using the combinatorial formula.
- Use a hash table (or dictionary) to count the frequency of the value (nums[i] - i) for each index. For each key in the hash table, compute the number of good pairs using the formula (frequency * (frequency - 1) / 2) and subtract the sum of these counts from the total pairs to get the number of bad pairs. The key trick is to transform the condition for a good pair, leading to an efficient grouping based on the computed key.