Count Number of Pairs With Absolute Difference K - Problem
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:
xifx >= 0-xifx < 0
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,2,1], k = 1
›
Output:
4
💡 Note:
Pairs with absolute difference 1: (0,1), (0,2), (1,3), (2,3). All have |nums[i] - nums[j]| = 1.
Example 2 — Larger Difference
$
Input:
nums = [1,3], k = 3
›
Output:
0
💡 Note:
No pairs exist where |nums[i] - nums[j]| = 3. Only pair is (0,1) with |1-3| = 2.
Example 3 — Zero Difference
$
Input:
nums = [3,2,1,5,1,4], k = 2
›
Output:
4
💡 Note:
Pairs with absolute difference 2: (0,2) |3-1|=2, (0,3) |3-5|=2, (0,4) |3-1|=2, (1,5) |2-4|=2
Constraints
- 1 ≤ nums.length ≤ 200
- 1 ≤ nums[i] ≤ 100
- 0 ≤ k ≤ 99
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code