Skip to content

Instantly share code, notes, and snippets.

@Gimcrack
Created July 25, 2023 16:58
Show Gist options
  • Save Gimcrack/96149db69cf553c26ac6db8ee05a504c to your computer and use it in GitHub Desktop.
Save Gimcrack/96149db69cf553c26ac6db8ee05a504c to your computer and use it in GitHub Desktop.
Get Products O(n)
<?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));
@Gimcrack
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment