Given two unique integer arrays $a and $b, and an integer target value $v, create a function to determine whether there is a pair of numbers that add up to the target value $v, where one number comes from one array $a and the other comes from the second array $b. Return true if there is a pair that adds up to the target value; otherwise, return false.
Examples
sumOfTwo([1, 2], [4, 5, 6], 5) ➞ true
sumOfTwo([1, 2], [4, 5, 6], 8) ➞ true
sumOfTwo([1, 2], [4, 5, 6], 3) ➞ false
sumOfTwo([1, 2], [4, 5, 6], 9) ➞ false
<?php
function sumOfTwo($arr1, $arr2, $element) {
// Convert arr1 into a hash set for quick lookups
$set = array_flip($arr1); // array_flip converts values into keys
foreach ($arr2 as $val) {
$complement = $element - $val;
if (isset($set[$complement])) { // Faster lookup
return true; // Return immediately if found
}
}
return false;
}
// Test cases
echo (sumOfTwo([1, 2], [4, 5, 6], 5) ? "true" : "false");
echo (sumOfTwo([1, 2], [4, 5, 6], 8) ? "true" : "false");
echo (sumOfTwo([1, 2], [4, 5, 6], 3) ? "true" : "false");
echo (sumOfTwo([1, 2], [4, 5, 6], 9) ? "true" : "false");
?>
Top comments (0)