The value range constraint is what unlocks the efficient solution here.
Use a frequency array to count occurrences of each value, then iterate through possible values and sum freq[v] * freq[v+k] for all v. This avoids O(n^2) pair checking and handles the modulo requirement. Since values are bounded by 1000, the solution is O(n + maxVal) time and O(maxVal) space.
Pro tip: Clarify that the modulo is applied only to the final count, not intermediate multiplications, to avoid unnecessary modulo operations and potential overflow. Also, mention that if k=0, the formula changes to freq[v]*(freq[v]-1)/2, but the problem states k>=1 so it's not needed.
Restate the problem: count index pairs (i,j) with i!=j and |arr[i]-arr[j]|=k, modulo 1e9+7. Note n up to 100,000 and values up to 1000, so O(n^2) is too slow.
Use a frequency array (or hash map) to count occurrences of each value. Since values are small (<=1000), an array of size 1001 is ideal.
For each value v from 1 to maxVal-k, add freq[v] * freq[v+k] to the total. This counts all unordered pairs with difference k exactly once.
Take the total modulo 1,000,000,007. If k=0, the formula would be different, but since k>=1, no special handling is needed. Also, ensure i!=j is satisfied because we only count distinct indices via frequency multiplication.
Time complexity: O(n + maxVal) where maxVal <= 1000. Space: O(maxVal). Test with small cases, e.g., arr=[1,2,3], k=1 -> 2 pairs.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.