DEV Community

Sharmin Shanta
Sharmin Shanta

Posted on

Product of Array Elements Except Self in PHP

Solution #1:

function productArray($arr, $n)
{
    // Base case
    if ($n == 1) {
        echo "0";
        return;
    }

    $left = [];
    $right = [];
    $prod = [];

    $left[0] = 1;
    $right[$n - 1] = 1;

    // Construct the left array
    for ($i = 1; $i < $n; $i++)
        $left[$i] = $arr[$i - 1] * $left[$i - 1];

    // Construct the right array
    for ($j = $n - 2; $j >= 0; $j--)
        $right[$j] = $arr[$j + 1] * $right[$j + 1];

    // Construct the product array
    // using left[] and right[]
    for ($i = 0; $i < $n; $i++)
        $prod[$i] = $left[$i] * $right[$i];

    // print the constructed prod array
    for ($i = 0; $i < $n; $i++)
        echo $prod[$i], " ";

    return;
}

// Driver Code
$arr = [2, 3, 5, 4, 6];
$n = count($arr);
echo "The product array is : \n";
productArray($arr, $n);
Enter fullscreen mode Exit fullscreen mode

Solution #2:

function productExceptSelf($nums) {
    // Determine the length of the input list 'nums'.
    $num_length = count($nums);

    // Initialize the answer list with 1's of the same length as 'nums'.
    $answer = array_fill(0, $num_length, 1);

    // 'left' will represent the cumulative product of elements to the left of the current element.
    $left = 1;
    for ($i = 0; $i < $num_length; $i++) {
        // Store the cumulative product in the 'answer' list at the current index 'i'.
        $answer[$i] = $left;
        // Update 'left' to include the product of the current element.
        $left *= $nums[$i];
    }

    // 'right' will represent the cumulative product of elements to the right of the current element.
    $right = 1;
    for ($i = $num_length - 1; $i >= 0; $i--) {
        // Multiply the existing value in 'answer' by the 'right' value which is the product of elements to the right of 'i'.
        $answer[$i] *= $right;
        // Update 'right' to include the product of the current element.
        $right *= $nums[$i];
    }

    // Return the 'answer' list which now contains the products except self.
    return $answer;
}

print_r(productExceptSelf([2, 3, 4, 5]));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)