Count Number of Pairs With Absolute Difference K - Problem
You're given an integer array nums and an integer k. Your task is to find how many pairs of indices (i, j) exist where i < j and the absolute difference between nums[i] and nums[j] equals exactly k.
The absolute difference |nums[i] - nums[j]| means:
- If
nums[i] >= nums[j], then|nums[i] - nums[j]| = nums[i] - nums[j] - If
nums[i] < nums[j], then|nums[i] - nums[j]| = nums[j] - nums[i]
Example: Given nums = [1, 2, 2, 1] and k = 1, the pairs (0,1), (0,2), (1,3), and (2,3) all have absolute difference of 1, so the answer is 4.
Input & Output
example_1.py β Basic Case
$
Input:
nums = [1,2,2,1], k = 1
βΊ
Output:
4
π‘ Note:
The pairs with absolute difference 1 are: (0,1): |1-2|=1, (0,2): |1-2|=1, (1,3): |2-1|=1, (2,3): |2-1|=1. Total: 4 pairs.
example_2.py β No Valid Pairs
$
Input:
nums = [1,3], k = 3
βΊ
Output:
0
π‘ Note:
There's only one pair (0,1) and |1-3|=2, which is not equal to k=3. So the answer is 0.
example_3.py β All Same Elements
$
Input:
nums = [3,2,1,5,1,4], k = 2
βΊ
Output:
4
π‘ Note:
The pairs with absolute difference 2 are: (0,1): |3-1|=2, (0,4): |3-1|=2, (2,5): |1-3|=2, (3,4): |5-3|=2. Wait, let me recalculate: (0,2): |3-1|=2, (0,4): |3-1|=2, (1,5): |2-4|=2, (2,5): |1-3|=2. Actually: (2,5): |1-3|=2, (0,2): |3-1|=2, (0,4): |3-1|=2, (1,5): |2-4|=2. Total: 4 pairs.
Visualization
Tap to expand
Understanding the Visualization
1
Meet Each Person
As each person arrives, check if any previous arrivals could be their dance partner
2
Check Height Difference
Look for people who are exactly k inches taller or shorter
3
Count Matches
Add the number of compatible partners to our running total
4
Record Arrival
Add the current person to our list for future matching
Key Takeaway
π― Key Insight: By checking for compatible partners as each person arrives (rather than comparing everyone with everyone), we achieve optimal O(n) performance while naturally maintaining the ordering constraint.
Time & Space Complexity
Time Complexity
O(n)
Single pass through array, each hash table operation is O(1) average case
β Linear Growth
Space Complexity
O(n)
Hash table can store up to n unique elements in worst case
β‘ Linearithmic Space
Constraints
- 1 β€ nums.length β€ 200
- 1 β€ nums[i] β€ 100
- 0 β€ k β€ 99
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code