easyArraysPattern: Two Pointers
Distance Between Pairs Solution
Problem Statement
Given a list of integers, find all pairs of elements that have a distance of 27.
Examples
Example 1:
Input:[1, 28, 7, 3, 9]
Output:[[0,4]]
Explanation: Only pair (0, 1) satisfies abs(timestamps[i] - timestamps[j]) == 27 and i < j
Example 2:
Input:[-4, 8, 1, 12, 5]
Output:[]
Explanation: No pairs satisfy abs(timestamps[i] - timestamps[j]) == 27 and i < j
Example 3:
Input:[1, 2, 3, 4, 5]
Output:[]
Explanation: No pairs satisfy abs(timestamps[i] - timestamps[j]) == 27 and i < j
Constraints
- The list can be of any size.
- The list can contain negative numbers.
- The distance of 27 can be negative.
Time: O(n log n) Space: O(n)
A more efficient way to solve this problem is to sort the list and use a two-pointer technique to find pairs with a distance of 27.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def find_pairs_with_distance27(arr): arr.sort(); left = 0; right = 1; pairs = []; while (right < len(arr) and left < right): if (abs(arr[right] - arr[left]) == 27): pairs.append([left, right]); left += 1; right += 1; elif (arr[right] < arr[left] + 27): right += 1; else: left += 1; return pairs;