래원

[LeetCode] 2364. Count Number of Bad Pairs (Python) 본문

알고리즘/LeetCode

[LeetCode] 2364. Count Number of Bad Pairs (Python)

Laewon Jeong 2025. 2. 9. 18:57

 

 

난이도: Medium

문제 설명


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.

 

제한 사항


  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

 

✏️ Solution(솔루션)

class Solution:
    def countBadPairs(self, nums: List[int]) -> int:
        n = len(nums)

        c = defaultdict(int)
        answer = n * (n-1)//2

        for i in range(n):
            c[nums[i] - i] += 1
        
        for k, v in c.items():
            if v > 1:
                answer -= v*(v-1)//2
        
        return answer

 

문제 설명에서 bad pair의 기준은 i<j일 때, j - i != nums[j] - nums[i] 라고 했다.

 

이를 다시 써보면 nums[i] - i != nums[j] - j로 표현할 수 있다.

 

따라서, nums의 요소를 탐색하면서 nums[i] - i의 값을 세었다.

 

왜냐하면 이 값을 동일하게 갖는 요소들의 개수를 세면 이들이 (i, j) 쌍을 이룰 때 good pair가 되기 때문이다.

 

이제, 전체 쌍의 개수에서 good pair의 개수를 빼면 bad pair의 개수를 구할 수 있다.


전체 쌍의 개수는 조합 공식인 n * (n-1) / 2 를 이용해 구할 수 있다.


그리고 good pair의 개수는 같은 nums[i] - i 값을 갖는 요소들의 개수를 v라고 했을 때, v * (v-1) / 2 로 계산된다.

 

결과적으로, nums를 순회하며 nums[i] - i 값을 세고, 이를 기반으로 good pair의 개수를 구한 후 전체 쌍에서 빼주는 방식으로 문제를 해결했다.


문제: 2364. Count Number of Bad Pairs

 

깃허브: github

 

algorithmPractice/LeetCode/2448-count-number-of-bad-pairs at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com