I am writing a function that takes in an array of integers and returns the number of unique pairs of integers that add up to a specific sum. For example, given the array [2, 4, 6, 2, 8, 4, 7, 2, 5, 9] and a sum of 10, the function should return 2 + the pairs number[].
function countPairs($arr, $sum) {
$pairCount = 0;
$pairs = [];
for ($i = 0; $i < count($arr); $i++) {
for ($j = $i + 1; $j < count($arr); $j++) {
if ($arr[$i] + $arr[$j] == $sum) {
$pairCount++;
$pairs[] = [$arr[$i], $arr[$j]];
}
}
}
return ['pairCount' => $pairCount, 'pairs' => $pairs];
}
this is what I got so far. it works but it doesn’t check whether a pair has already been counted or not, which can result in duplicates. what should do ?
3
Answers
One solution is combine the values together and make them the key. Then just check to see if the array is in the pairs array. I also sorted the values so that 8,2 and 2,8 will be the same.
This should so the trick:
It checks if the current pair of values has already been counted and stored in the
$pairs
array. If the pair is not in the array yet, it is added to the$pairs
array along with the number of unique pairs,$pairCount
.It’s far more simple to filter duplicates from the array first, rather than trying to figure out if your result has already been seen.
Then you can also sort the input and then quit early if you’re touching values that are too large.
Lastly, finding duplicates and counting the result are two separate operations which don’t necessarily need to be coupled like this.
Output:
You could even go a step further and do a binary search on the array for
$sum - $arr[$i]
instead of looping through the entire sub-array in the inner loop.