I was given an array like this array(1,5,3,4,2);
Say k=2
, I'm supposed to find out the count of pairs whose difference is 2. In this case it should return 3 because 5-3, 4-2, 3-1
Here's what I have tried. It works fine I'm looping through the array twice O(n^2)
complexity, I'm wondering if there is a better way to achieve this.
$arr = array(1,5,3,4,2);
$k =2;
function find_pairs($arr, $k)
{
$count = 0;
for ($i=0 ; $i<= count($arr)-1 ; $i++)
{
for ($j=$i+1; $j <= count($arr)-1 ; $j++)
{
if ($arr[$i]-$arr[$j] == $k || $arr[$j]-$arr[$i]==$k)
{
$count++;
}
}
}
return $count;
}
echo find_pairs($arr, $k);
Thanks