Count Number of Pairs With Absolute Difference K

You have an integer array nums and another integer k. Your task is to find the number of pairs (i, j) where i < j, and the absolute difference between nums[i] and nums[j] is equal to k.

Solution Approach

Here’s a step-by-step guide to solve this problem:

  1. Initialize a Counter: Start with a variable to keep track of the count of pairs with the absolute difference k.

  2. Iterate Through the Array: Use two nested loops to iterate through all pairs of (i, j) where i < j.

  3. Calculate Absolute Difference: For each pair, calculate the absolute difference between nums[i] and nums[j].

  4. Check the Difference: If the absolute difference is equal to k, increment the counter.

  5. Return the Result: Return the count after iterating through all pairs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        count = 0 # Step 1: Initialize the counter

        # Step 2: Iterate through all pairs (i, j) where i < j
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):

                # Step 3: Calculate absolute difference
                difference = abs(nums[i] - nums[j])

                # Step 4: Check if the difference is equal to k
                if difference == k:
                    count += 1 # Increment the counter

        # Step 5: Return the result
        return count

Key Takeaways

  • We are looking for pairs (i, j) where the absolute difference between the corresponding elements is k.
  • We need to iterate through all possible pairs and calculate the absolute difference to find the count of such pairs.
  • Using two nested loops and a counter variable allows us to solve this problem in a straightforward manner.