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:

  • x if x >= 0
  • -x if x < 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: 3
💡 Note: Pairs with absolute difference 2: (0,1) |3-1|=2, (1,2) |2-4|=2, (2,5) |1-3|=2

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 100
  • 0 ≤ k ≤ 99

Visualization

Tap to expand
Count Pairs with Absolute Difference Knums = [1,2,2,1], k = 11221i=0i=1i=2i=3|1-2|=1 ✓|1-2|=1 ✓|2-1|=1 ✓|2-1|=1 ✓Result: 4 pairs
Understanding the Visualization
1
Input
Array [1,2,2,1] with k=1
2
Process
Find all pairs with absolute difference k
3
Output
Count of valid pairs: 4
Key Takeaway
🎯 Key Insight: Use frequency counting to avoid checking all pairs - for each number, just check if (num±k) exists in the map
Asked in
Amazon 15 Microsoft 12
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen