Count Number of Pairs With Absolute Difference K

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.

The value of |x| is defined as:

  • x if x >= 0.
  • -x if x < 0.
Example 1
Inputnums = [1,2,2,1], k = 1
Output4
The pairs with an absolute difference of 1 are the four pairs formed by each 1 with each 2.
Example 2
Inputnums = [1,3], k = 3
Output0
There are no pairs with an absolute difference of 3.

Constraints

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100
  • 1 <= k <= 99

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate