Created
July 25, 2023 16:58
-
-
Save Gimcrack/96149db69cf553c26ac6db8ee05a504c to your computer and use it in GitHub Desktop.
Get Products O(n)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$input = [-1,1,0,-3,3]; | |
function getProducts(array $input) { | |
// initialize output array with 1s | |
$output = array_map(fn($el) => 1, $input); | |
$length = count($input); | |
// multiply each element by the elements before it | |
$temp=1; | |
for($ii=0; $ii<$length; $ii++) { | |
$output[$ii] *= $temp; | |
$temp *= $input[$ii]; | |
} | |
// multiply each element by the elements after it | |
$temp=1; | |
for($ii=$length-1; $ii>=0; $ii--) { | |
$output[$ii] *= $temp; | |
$temp *= $input[$ii]; | |
} | |
return $output; | |
} | |
print_r(getProducts($input)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This function computes the products of the members of the input array excluding the member at the current position. It multiplies each element by the elements that come before it, then it multiplies by the elements that come after it.
It has O(n) complexity.