Problem Description
Given an integer array nums and an integer k, we are required to return the number of pairs (i, j) where i < j such that the absolute difference |nums[i] - nums[j]| equals k.
Key Insights
- Use a frequency table (hash table) to count the occurrences of each number.
- For each unique number, check if the number + k exists in the frequency table.
- Multiply the frequencies of number and number+k to get the count of valid pairs for that particular value.
- Since k is always >= 1, we can safely use the frequency method without worrying about handling the k == 0 case.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the array, as we traverse the list once to build the frequency table and then iterate over a limited range of possible values. Space Complexity: O(n) in the worst-case scenario for storing the frequency counts.
Solution
We use a hash table (or dictionary) to count the occurrences of each number in the array. For each unique number in the hash table, we look for the number + k in the table. If it exists, then every occurrence of the current number can pair with every occurrence of (current number + k). Multiplying these two counts gives the number of valid pairs for that number. The total pair count is the sum of valid pairs from all numbers.