Loading...
Loading...
Loading...
Given n order amounts and a number k, count the pairs of positions i < j whose amounts differ by exactly k, that is |a[i] - a[j]| = k. Repeated amounts count as different positions.
Example
Input
5 2 1 5 3 4 2
Output
3
The pairs are 1 and 3, 5 and 3, and 4 and 2: 3 pairs.
Try the problem first. Open one hint at a time.
Checking every pair is O(n^2). Count how many times each value has appeared so far.
For each value v, earlier values v - k and v + k each form a pair with it. Since k is at least 1, the two are different values.
Write your Python code, run it on the examples and submit it to hidden tests.
Solve in the editor