Perl Weekly Challenge 056: Diff-K and Path Sum
Diff-K
You are given an array @N of positive integers (sorted) and another non negative integer $k. Write a script to find if there exists 2 indices $i and $j such that$A[$i] - $A[$j] == $k and $i != $j
. It should print the pairs of indices, if any such pairs exist.Example:
@N = (2, 7, 9); $k = 2;
Output: 2, 1
I totally ignored the fact that the input array is sorted. My solution works for any input array, but it’s still rather efficient.
The basic trick is that we don’t have to compute $A[$i] - $A[$j]
for each combination or $i
and $j
. We know $k
from the very beginning, so we can just iterate the array for the first time to store it in a hash, and iterate it for the second time to check the hash whether the corresponding number exists in the array.