MediumNo. 2364
Count Number of Bad Pairs — LeetCode 2364 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Array, Hash Table, Math, Counting
- Reading time
- 2 min
- Source
- leetcode.com
The 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].
Example
- Input
- nums = [4,1,3,3]
- Output
- 5
- Explanation
- The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
Python solution
class Solution:
def countBadPairs(self, nums: List[int]) -> int:
cnt = Counter()
ans = 0
for i, x in enumerate(nums):
ans += i - cnt[i - x]
cnt[i - x] += 1
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the length of the array nums
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2364. Count Number of Bad Pairs is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0914 | X of a Kind in a Deck of Cards | Easy |
| 1512 | Number of Good Pairs | Easy |
| 1814 | Count Nice Pairs in an Array | Medium |
| 1994 | The Number of Good Subsets | Hard |
| 2001 | Number of Pairs of Interchangeable Rectangles | Medium |
| 2442 | Count Number of Distinct Integers After Reverse Operations | Medium |
Frequently asked questions
- How hard is LeetCode 2364. Count Number of Bad Pairs?
LeetCode 2364. Count Number of Bad Pairs is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2364. Count Number of Bad Pairs?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2364. Count Number of Bad Pairs?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
- What topics does LeetCode 2364. Count Number of Bad Pairs cover?
LeetCode 2364. Count Number of Bad Pairs is tagged Array, Hash Table, Math and Counting on LeetCode.