DEV Community

Himanshu Joshi
Himanshu Joshi

Posted on

DSA Problem #1 Determine If Two Numbers Add up to a Target Value (PHP)

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");
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay