⚡Flashcard Drill➔
NeetCode #153LC-2364MediumArrays & Hashing
← Back to All Problems

#153 · #2364 · Count Number of Bad Pairs(统计坏数对的数目)

📌 Problem Statement & Constraints

You are given a 0-indexed integer array nums. A pair (i, j) is bad if i < j and j - i != nums[j] - nums[i]. Return the total number of bad pairs. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^9.

💡 Core Algorithmic Approaches

  1. Counting bad pairs directly is awkward, but the complement is easy: a pair is good when j - i == nums[j] - nums[i].
  2. Rearrange the good condition: nums[i] - i == nums[j] - j. So group indices by the key nums[i] - i.
  3. A group of size c contributes C(c, 2) good pairs.
  4. The answer is the total number of pairs n * (n - 1) / 2 minus the good pairs.

💻 Benchmark Python3 Implementation

class Solution:
    def countBadPairs(self, nums: List[int]) -> int:
        from collections import Counter
        n = len(nums)
        total = n * (n - 1) // 2
        # good pairs: equal values of (nums[i] - i)
        cnt = Counter(nums[i] - i for i in range(n))
        good = sum(c * (c - 1) // 2 for c in cnt.values())
        return total - good

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass to build the key counts.
💾 Space Complexity
O(n) for the counter.

⚠️ Interview Pitfalls & Follow-ups

  • Counting bad pairs directly with a double loop: O(n^2), far too slow at 10^5.
  • Using the wrong key: the condition is nums[i] - i == nums[j] - j, not nums[i] + i.
  • Forgetting to subtract from the total: the grouping counts good pairs, and the answer is the complement.
  • Assuming the answer fits in 32 bits: n = 10^5 gives about 5 * 10^9 pairs, so a 64-bit type (or Python's unbounded int) is required.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

统计坏数对的数目

给你一个下标从 0 开始的整数数组 nums。如果 i &lt; j 且 j − i != nums[j] − nums[i] ,那么我们称 (i, j) 是一个 坏数对 。请你返回数组中所有坏数对数目。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9。

核心要点

  • 转化为「好数对」的补集(标准解) :总对数减去好数对数量。
  • 好数对的条件 : j − i == nums[j] − nums[i] ,移项得 nums[j] − j == nums[i] − i 。因此只需统计 nums[k] − k 相同的下标对数。
  • 哈希表计数 :遍历数组,维护 cnt[key] 表示之前出现过多少个 nums[k] − k == key 的下标。当前下标与其中每一个都构成好数对,因此 good += cnt[key] 。
  • 总对数 : n(n−1)/2 。答案 = 总对数 − 好数对。

常见陷阱

  • 直接双重循环统计坏数对 :O(n²) 在 n = 10^5 时必然超时。必须用「总数 − 好数对」的补集思路。
  • 把条件写成 nums[j] + j == nums[i] + i :移项方向错了。正确条件是 nums[j] − j == nums[i] − i 。
  • 好数对累加时用 cnt[key] + 1 :当前下标只能与 之前 的下标配对(i &lt; j),不能与自己配对。
  • 担心大数溢出 :Python 整数无溢出;C++/Java 中 n = 10^5 时总对数约 5 × 10^9,超出 int 范围,需用 long long。

参考实现

from collections import defaultdict

class Solution:
    def countBadPairs(self, nums: list[int]) -> int:
        n = len(nums)
        total = n * (n - 1) // 2        # 所有下标对
        cnt = defaultdict(int)
        good = 0
        for i, x in enumerate(nums):
            key = x - i                 # 好数对的等价条件
            good += cnt[key]            # 与之前每个同 key 的下标构成好数对
            cnt[key] += 1
        return total - good