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

2025. 2. 9. 18:57·알고리즘/LeetCode

 

 

난이도: 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

 

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 1910. Remove All Occurrences of a Substring (Python)  (0) 2025.02.11
[LeetCode] 3174. Clear Digits (Python)  (0) 2025.02.10
[LeetCode] 2349. Design a Number Container System (Python)  (0) 2025.02.08
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)  (1) 2025.02.07
[LeetCode] 1726. Tuple with Same Product (Python)  (0) 2025.02.06
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 1910. Remove All Occurrences of a Substring (Python)
  • [LeetCode] 3174. Clear Digits (Python)
  • [LeetCode] 2349. Design a Number Container System (Python)
  • [LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    dfs
    코딩테스트
    도커
    파이썬
    프로그래머스
    우선순위큐
    티스토리챌린지
    백트래킹
    programmers
    Python
    리트코드
    Kubernetes
    알고리즘
    문자열
    분산
    쿠버네티스
    이진탐색
    그래프
    아파치 하둡
    오블완
    DP
    docker
    아파치 스파크
    leetcode
    분산처리
    누적합
    heapq
    String
    Apache Spark
    BFS
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2364. Count Number of Bad Pairs (Python)
상단으로

티스토리툴바