Similar Problems

Similar Problems not available

Count Number Of Pairs With Absolute Difference K - Leetcode Solution

Companies:

LeetCode:  Count Number Of Pairs With Absolute Difference K Leetcode Solution

Difficulty: Easy

Topics: hash-table array  

Problem Statement:

Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.

Example:

Input: nums = [1,2,2,1], k = 1 Output: 4 Explanation: The pairs with an absolute difference of 1 are:

  • [1,2,2,1] with indices (0,1)
  • [1,2,2,1] with indices (0,3)
  • [1,2,2,1] with indices (1,2)
  • [1,2,2,1] with indices (2,3)

Solution Approach:

  • Initialize a count variable to zero

  • Create a set of unique numbers from the nums array, this will remove duplicates.

  • Iterate for each element in this array, we know that abs(num1 - num2) = k, hence we consider two cases here:

      if num+k in the set, increment the count variable by 1
      if num-k in the set, increment the count variable by 1
    
  • Return the count variable

Code in Python:

class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        unique_nums = set(nums)
        count = 0
        for num in unique_nums:
            if num+k in unique_nums:
                count += 1
            if num-k in unique_nums:
                count += 1
        return count

Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(n), to store the unique numbers in the set.

Count Number Of Pairs With Absolute Difference K Solution Code

1