1310. Near Pair Band Count
Sensors are mounted along a pipeline and nums[i] is the pressure reported by sensor i. Two sensors are linked when their positions satisfy i < j and j - i <= d, and the sum of their pressures lies in the closed band [lo, hi].
Given nums, d, lo and hi, return the number of linked pairs of positions. Pairs are counted by position, so equal pressures at different positions give different pairs. The bounds can be as large as 2 * 10^9, which does not fit in a 32-bit signed integer once added to a pressure, so use 64-bit arithmetic for them.
Looking at all pairs is too slow when the data grows. Keep only the previous d pressures in an indexed structure over their ranks and answer each position with two rank lookups. Aim for O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [1,5,3,2]d = 2lo = 4hi = 6
- Output:
- 3
- Explanation:
The pairs (0,1), (0,2) and (2,3) have sums 6, 4 and 5, which lie in the band, while (1,2) and (1,3) have sums 8 and 7, so the count is 3.
Example 2
- Input:
- nums = [2,2,2]d = 1lo = 4hi = 4
- Output:
- 2
- Explanation:
Only neighbouring positions may pair, and both neighbouring pairs sum to 4, so the count is 2.
Example 3
- Input:
- nums = [0,0]d = 1lo = 1hi = 5
- Output:
- 0
- Explanation:
The only pair sums to 0, which is below the band, so the count is 0.
Constraints
-
1 ≤ nums.length ≤ 1000 -
1 ≤ d ≤ nums.length -
0 ≤ nums[i] ≤ 109 -
0 ≤ lo ≤ hi ≤ 2 * 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)