Two Sum

Find indices of two numbers in an array that add up to a target value using a hash map for O(n) time complexity.

Code

Algorithms
$seen = [];
$result = null;
foreach ($arr as $i => $num) {
    $complement = $target - $num;
    if (isset($seen[$complement])) {
        $result = [$seen[$complement], $i];
        break;
    }
    $seen[$num] = $i;
}
return $result;

Parameters

Array of numbers

Target sum

Server

More PHP Snippets