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: 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
Count Pairs With Absolute Difference K INPUT nums array: 1 i=0 2 i=1 2 i=2 1 i=3 k = 1 Find pairs where: |nums[i] - nums[j]| == k with i < j ALGORITHM (Hash) 1 Build Hash Map Count frequency of each num num: count 1: 2 2: 2 2 For each num Check if (num + k) exists 3 Count valid pairs count[num] * count[num+k] Pairs Found: num=1: 1+1=2 exists count[1]*count[2] = 2*2 = 4 Total pairs = 4 4 Return count FINAL RESULT Valid Pairs (i, j): (0, 1) |1-2|=1 (0, 2) |1-2|=1 (1, 3) |2-1|=1 (2, 3) |2-1|=1 Output: 4 OK - 4 pairs found! Key Insight: Using a hash map to store frequencies allows O(n) time complexity instead of O(n^2) brute force. For each unique number, we check if (num + k) exists and multiply their counts to get valid pairs. TutorialsPoint - Count Number of Pairs With Absolute Difference K | Hash Approach
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