Given an array arr of distinct integers and a nonnegative integer
k
, write a function findPairsWithGivenDifference that returns an array of all pairs[x,y]
in arr, such thatx - y = k
. If no such pairs exist, return an empty array.In your solution, try to reduce the memory usage while maintaining time efficiency. Prove the correctness of your solution and analyze its time and space complexities.
Note: the order of the pairs in the output array should maintain the order of the y element in the original array.
Examples:
input:
arr = [0, -1, -2, 2, 1], k = 1 output: [[1, 0], [0, -1], [-1, -2], [2, 1]]
input:
arr = [1, 7, 5, 3, 32, 17, 12], k = 17
output: []
Constraints:
[time limit] 5000ms
[input] array.integer arr
0 ≤ arr.length ≤ 100 [input]integer k
k ≥ 0 [output] array.array.integer
def find_pairs_with_given_difference(arr, k):
numbers = set()
output = []
# insert arr element into set
for i in range(len(arr)):
numbers.add(arr[i])
# loop through the entire array
for i in range(len(arr)):
difference = arr[i]
if difference - k in numbers:
output.append([difference,(difference - k)])
return output
Test case #1
Input: [4,1], 3
Expected: [[4,1]]
Actual: [[4, 1]]
Test Case #2
Input: [1,5,11,7], 4
Expected: [[5,1],[11,7]]