Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109
Solution
Video explanation
Here is the video explaining below methods in detail. Please check it out:
Method 1 - Naive
The naive approach involves using two nested loops to check every possible pair (i, j) and determine if it qualifies as a bad pair. Simply iterate through the array, and for each index i, compare it with every other index j where j > i.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n^2)due to the nested loops. - 🧺 Space complexity:
O(1)as we only need a few extra variables for counting.
Method 2 - Using Hashmap + Maths
To solve this problem, we need to count the number of pairs (i, j) such that i < j and j - i != nums[j] - nums[i]. Rearranging the equation, we get:
$$ j - i = nums[j] - nums[i] $$ $$ j - nums[j] = i - nums[i] $$ Let’s call: $$ k_j = j - nums[j] $$ $$ k_i = i - nums[i] $$
We observe that for a pair (i, j) to not be a “bad pair”:
$$
k_i = k_j
$$
So we need to count pairs where this condition does not hold.
Approach
- Use a hashmap to store the counts of each value of $k_i$ we encounter.
- Traverse the array and for every index
j, compute $k_j$. Check how many $k_i$ values (from previously seen indices) equal $k_j$ and use this to determine how many pairs(i, j)are not bad pairs. - The total pairs
(i, j)fori < jare $\frac{n(n-1)}{2}$. - Subtract the number of good pairs from the total pairs to get the number of bad pairs.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n)since we traverse the array once. - 🧺 Space complexity:
O(n)due to the hashmap storage.