Count Pairs with Difference At Most K
Given a 0-indexed sorted array of integers nums and a non-negative integer k, return the total number of index pairs (i, j) such that 0 <= i < j < nums.length and nums[j] - nums[i] <= k.
Your solution should take advantage of the sorted property of the array to solve the problem in linear time using the two-pointer technique.
[ "[1, 2, 3, 5, 8]", "3" ]
Explanation. The valid index pairs (i, j) with difference <= 3 are (0,1), (0,2), (1,2), (1,3), (2,3), and (3,4).
[ "[1, 5, 10, 15]", "2" ]
Explanation. No pair of elements has a difference of 2 or less.
[ "[2, 2, 2, 2]", "0" ]
Explanation. All 6 pairs of indices have elements with a difference equal to 0, which is <= 0.
[ "[1, 4, 7, 10]", "3" ]
Explanation. The pairs (0,1), (1,2), and (2,3) each have a difference of exactly 3.
[ "[10]", "5" ]
Explanation. An array with fewer than 2 elements has no valid index pairs.
Follow-up: How would you solve this problem if the array were not pre-sorted, and what would be the resulting time complexity?
1 <= nums.length <= 10^5 0 <= nums[i] <= 10^9 nums is sorted in non-decreasing order. 0 <= k <= 10^9
- Views
- 7