LeetCode solutions

2448. Count Number of Bad Pairs

My accepted Python solution to LeetCode problem 2448, Count Number of Bad Pairs, running in 83ms.

  • Difficulty: Medium
  • Python
  • Runtime 83ms
  • Memory 36MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 83ms, memory 36MB, accepted 2026-01-02.

python
class Solution:
    def countBadPairs(self, nums: List[int]) -> int:
        from collections import defaultdict
        n = len(nums)
        total_pairs = n * (n - 1) // 2
        
        # Count pairs where nums[i] - i == nums[j] - j (good pairs)
        count = defaultdict(int)
        good_pairs = 0
        
        for i, num in enumerate(nums):
            diff = num - i
            good_pairs += count[diff]
            count[diff] += 1
        
        return total_pairs - good_pairs

Source