Skip to content

2364. Count Number of Bad Pairs #1291

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to count the number of bad pairs in a given array. A pair (i, j) is considered bad if i < j and j - i != nums[j] - nums[i]. Directly checking each pair would be inefficient, so we use a mathematical approach to optimize the solution.

Approach

  1. Identify Good Pairs: A pair (i, j) is good if j - i == nums[j] - nums[i]. This can be rearranged to nums[i] - i == nums[j] - j. Thus, elements with the same value of (nums[i] - i) form groups of good pairs.
  2. Count Good Pairs: For each group of elements with the same (nums[i] - i) value, the number of good pairs is given by the combination formula m*(m-1)/2, where m is the size of the group.
  3. Calculate Total Pairs: The total number of pairs (i,…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Feb 9, 2025
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Feb 9, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Feb 9, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants