Skip to content

Instantly share code, notes, and snippets.

@khooz
Last active December 29, 2016 16:57
Show Gist options
  • Save khooz/182fece20b67db76d1c4c29317032036 to your computer and use it in GitHub Desktop.
Save khooz/182fece20b67db76d1c4c29317032036 to your computer and use it in GitHub Desktop.
Here's a more complete solution for Google's Example Coding/Engineering Interview video at https://youtu.be/XKu_SEDAykw
<?php
// PHP ^7.1
$ar1 = [1,2,5,9,-1,3,4,5]; // test array #1
$ar2 = [1,2,4,4,9,3,4,5,3]; // test array #2
/**
* Function that finds indices of x-complements to an element in an array
*
* @param array arr an array of integer/float numbers
* @param int sum the base for complements
*
* @return array|null an array that shows indices of element and it's complements if found any, null otherwise
*/
function find_complements(array $arr, int $sum): ?array {
// hash table of x-complements found
$hash_comp = [];
// hash table of elements
$hash_elem = [];
// final output
$res = [];
// iterating over each element: Θ(n)
foreach($arr as $idx => $elem){
$comp = $sum - $elem;
// if complement is found in complements' hash table, then we have already met an element that its complemet matches current element. Hence, this is a solution.
if (isset($hash_comp[$comp]))
{
isset($res[$elem]) ?? $res[$elem] = [];
// filling hash tables
$hash_comp[$elem][] = $idx;
$hash_elem[$elem][] = $idx;
// addint current element and its complements to the final results "BY REFERENCE", to let hash tables be completed on later iteration.
$res[$elem]['element_idx'] = &$hash_elem[$elem];
$res[$elem]['complement_idx'] = &$hash_comp[$comp];
// keep only the smallest results since each result carries the complements too.
switch ($elem <=> $comp){
case -1:{
unset($res[$comp]);
break;
}
case 1:{
unset($res[$elem]);
break;
}
}
continue;
}
// filling hash tables
$hash_comp[$elem][] = $idx;
$hash_elem[$elem][] = $idx;
}
return $res ?? null;
}
// commencing test
var_dump(find_complements($ar1,8));
var_dump(find_complements($ar2,8));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment