#2006
Count Number of Pairs With Absolute Difference K
EasyArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a HashMap allows us to count occurrences of each number, making it easy to find how many numbers can form valid pairs with a given number. This significantly reduces the number of comparisons needed.
⚙️
Algorithm
5 steps- 1Step 1: Create a HashMap to count occurrences of each number in the array.
- 2Step 2: Initialize a counter to 0.
- 3Step 3: For each unique number in the HashMap, check if the number + k and number - k exist in the map.
- 4Step 4: If they exist, multiply their counts and add to the counter.
- 5Step 5: Return the counter.
solution.py8 lines
1def countKDifference(nums, k):
2 from collections import Counter
3 count = 0
4 num_count = Counter(nums)
5 for num in num_count:
6 count += num_count[num] * num_count.get(num + k, 0)
7 count += num_count[num] * num_count.get(num - k, 0)
8 return count // 2ℹ
Complexity note: The time complexity is O(n) because we traverse the array once to count occurrences and then iterate through the unique numbers. The space complexity is O(n) due to the HashMap storing counts of each number.
- 1Using a HashMap can significantly reduce the number of comparisons needed.
- 2Understanding absolute differences can help simplify the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.