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 <= 1051 <= nums[i] <= 109This approach involves checking every possible pair of indices (i, j) where i < j and seeing if they satisfy the condition j - i != nums[j] - nums[i]. This will involve nested loops and checking the condition directly.
The C solution uses two nested loops to iterate through all pairs of indices. The outer loop iterates through each element, and the inner loop checks for every element succeeding it. If the condition for a bad pair is satisfied, we increment the counter. The solution is straightforward but not optimal for large inputs due to its O(n^2) complexity.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2)
Space Complexity: O(1)
To improve upon the brute force method, this approach introduces the concept of a hash map (or dictionary) to track the counts of differences calculated by "nums[i] - i". Using this, we can efficiently compute the number of good pairs and then derive the number of bad pairs from it.
The C implementation uses an array to simulate the hash map functionality, storing differences and their occurrences. Each difference is used to quickly calculate how many good & bad pairs exist as the input is processed. This efficient algorithm reduces time complexity to nearly O(n) via its single pass nature.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Brute Force Approach | Time Complexity: O(n^2) |
| Optimized Approach using Hash Maps | Time Complexity: O(n) |
Count the Number of Fair Pairs - Leetcode 2563 - Python • NeetCodeIO • 15,313 views views
Watch 9 more video solutions →Practice Count Number of Bad Pairs with our built-in code editor and test cases.
Practice on FleetCode