Design Gurus Logo
Count Number of Pairs With Absolute Difference K (easy)

Problem Statement

Given an array of integers nums and a positive integer k, return the number of pairs (i, j) where i < j and the absolute difference of nums[i] and nums[j] should be equal to k. In other words, |nums[i] - nums[j]| == k.

Examples

  • Example 1:

    • Input: nums = [1, 3, 5, 7], K = 2
    • Expected Output: 3
    • Justification: The pairs with an absolute difference of 2 are (1, 3), (3, 5), and (5, 7).
  • Example 2:

    • Input: nums = [4, 4, 4, 4], K = 1
    • Expected Output: 0
    • Justification: Each pair of the same elements has an absolute difference of 0. So, there are no pairs that have absolute difference 1.
  • Example 3:

    • Input: nums = [1,3,4,5,2], K = 2
    • Expected Output: 3
    • Justification: The pairs that satisfy the condition are (1, 3), (3, 5), and (4, 2).

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory