Count Number of Pairs With Absolute Difference K - Solution & Explanation
Problem Statement
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.
Example 1:
Input: nums = [1,2,2,1], k = 1 Output: 4 Explanation: The pairs with an absolute difference of 1 are: - [1,2,2,1] - [1,2,2,1] - [1,2,2,1] - [1,2,2,1]
Example 2:
Input: nums = [1,3], k = 3 Output: 0 Explanation: There are no pairs with an absolute difference of 3.
Example 3:
Input: nums = [3,2,1,5,4], k = 2 Output: 3 Explanation: The pairs with an absolute difference of 2 are: - [3,2,1,5,4] - [3,2,1,5,4] - [3,2,1,5,4]
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 1001 <= k <= 99
Approach Overview
Problem Overview: Given an integer array nums and an integer k, count the number of index pairs (i, j) such that i < j and |nums[i] - nums[j]| = k. The task is essentially pair counting with a fixed absolute difference constraint.
Approach 1: Brute Force Pair Check (O(n2) time, O(1) space)
The most direct solution checks every possible pair. Use two nested loops where the outer loop picks index i and the inner loop scans all indices j > i. For each pair, compute abs(nums[i] - nums[j]) and increment a counter when the difference equals k. This approach does not require additional data structures and works for any input order. However, it performs n(n-1)/2 comparisons, leading to O(n2) time complexity. It’s acceptable for small arrays and useful as a baseline to verify correctness before implementing a faster method.
Approach 2: Hash Map Frequency Counting (O(n) time, O(n) space)
A more efficient strategy uses a hash map to track how many times each value has appeared while iterating through the array. For every element x, you check whether x - k or x + k has already been seen. If they exist in the map, their frequencies represent valid pairs that satisfy the difference condition. Update the pair count accordingly, then store or increment the frequency of x in the map. Each lookup and update is O(1) on average, producing an overall O(n) time complexity with O(n) space for the frequency table.
This approach works because the difference condition can be rewritten as a - b = k or b - a = k. A hash lookup instantly tells you how many previously processed numbers satisfy either equation. The technique is a common pattern when solving pair problems with constraints on sums or differences.
The optimized method heavily relies on hash tables for constant‑time lookups and uses ideas similar to frequency tracking problems in counting. Since the input is simply scanned once, it scales efficiently even for large arrays typical in interview settings. The underlying data is still an array, but the hash map transforms the pair search from quadratic to linear time.
Recommended for interviews: Start by explaining the brute force approach to demonstrate understanding of the pair condition. Then move to the hash map solution, which reduces the complexity from O(n2) to O(n). Interviewers typically expect the hash-based counting approach because it shows familiarity with frequency maps and pair‑difference transformations.
Approach 1: Brute Force Approach
The simplest method is to check every possible pair of indices i and j (where i < j) and see if the absolute difference between nums[i] and nums[j] is equal to k. This involves a nested loop where the outer loop iterates through each element, and the inner loop checks each subsequent element for the condition.
The C code uses a nested loop to check each possible pair (i, j) in the array, calculating the absolute difference and checking if it equals k. The function returns the count of such pairs. The abs() function is used to compute the absolute difference.
Complexity
Time Complexity: O(n2), where n is the number of elements in the array.
Space Complexity: O(1), since no additional data structures are used.
Approach 2: Optimized Approach Using Hashmap
The optimized approach uses a hashmap (or dictionary) to store the frequency of each number in the array. As we traverse the array, we can quickly check how many numbers (based on their frequency stored in the hashmap) can form a valid pair with the currently considered number. This method reduces the need to examine each pair explicitly and improves the efficiency.
In this C solution, a frequency array `frequency` is used to keep track of the count of each number nums[i] encountered so far. For each number, we check potential pairs formed with nums[i] - k and nums[i] + k by looking up their counts in the frequency array.
Complexity
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as the space used for the frequency count is constant and depends on the constraint.
Approach 3: Brute Force Enumeration
We notice that the length of the array nums does not exceed 200, so we can enumerate all pairs (i, j), where i < j, and check if |nums[i] - nums[j]| equals k. If it does, we increment the answer by one.
Finally, we return the answer.
The time complexity is O(n^2), and the space complexity is O(1). Here, n is the length of the array nums.
Approach 4: Hash Table or Array
We can use a hash table or array to record the occurrence count of each number in the array nums. Then, we enumerate each number x in the array nums, and check if x + k and x - k are in the array nums. If they are, we increment the answer by the sum of the occurrence counts of x + k and x - k.
Finally, we return the answer.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.
Complexity Comparison
| Approach | Complexity |
|---|---|
| Brute Force Approach | Time Complexity: O(n2), where n is the number of elements in the array. |
| Optimized Approach Using Hashmap | Time Complexity: O(n), where n is the number of elements in the array. |
| Brute Force Enumeration | — |
| Hash Table or Array | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Pair Check | O(n^2) | O(1) | Small input sizes or when demonstrating the basic pair comparison logic. |
| Hash Map Frequency Counting | O(n) | O(n) | General case and interview scenarios where efficient pair counting is required. |
Video Solution
LeetCode 2006: Count Number of Pairs With Absolute Difference K • Engineering Digest • 4,296 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Count Number of Pairs With Absolute Difference K easy or hard?
Count Number of Pairs With Absolute Difference K Python/Java solution
How to solve Count Number of Pairs With Absolute Difference K in O(n)?
What is the best approach for Count Number of Pairs With Absolute Difference K?
Is Count Number of Pairs With Absolute Difference K asked at Google/Amazon/Meta?
What data structure is used in Count Number of Pairs With Absolute Difference K?
What is the time complexity of Count Number of Pairs With Absolute Difference K?
Ready to solve this problem?
Practice Count Number of Pairs With Absolute Difference K with our built-in code editor and test cases.
Practice on FleetCode