Skip to content
LC-2364 Medium LeetCode

2364. Count Number of Bad Pairs

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 54% Topics: Array, Hash Table, Math, Counting
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

import collections


# freq table
class Solution(object):
    def countBadPairs(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = len(nums)*(len(nums)-1)//2
        cnt = collections.Counter()
        for i, x in enumerate(nums):
            result -= cnt[x-i]
            cnt[x-i] += 1
        return result

Solution from kamyu104/LeetCode-Solutions · MIT