How to product of array except self (arr[i] is equal to the product of all the elements except arr[i]) in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Computes product of array except self.
// nums   = input slice
// returns a new slice containing the result
func productExceptSelf(nums []int) []int {
    size := len(nums)
    answer := make([]int, size)

    // ---- Prefix products ----
    // answer[i] gets the product of all elements before i
    prefix := 1
    for i := 0; i < size; i++ {
        answer[i] = prefix      // store prefix product
        prefix *= nums[i]       // update prefix
        // Example for nums = {5,2,3,4}:
        // prefix values: 1, 5, 10, 30
    }

    // ---- Suffix products ----
    // Multiply each answer[i] by product of all elements after i
    suffix := 1
    for i := size - 1; i >= 0; i-- {
        answer[i] *= suffix     // combine prefix * suffix
        suffix *= nums[i]       // update suffix
        // suffix values: 1, 4, 12, 24, 120
        // final answer: 24, 60, 40, 30
        // 24 (24*1) 60 (12*5) 40 (10*4) 30 (30*1)
    }

    return answer
}

func main() {
    arr := []int{5, 2, 3, 4}

    result := productExceptSelf(arr)

    fmt.Print("Result: ")
    for _, x := range result {
        fmt.Print(x, " ")
    }
}



/*
run:

Result: 24 60 40 30 

*/

 



answered Jan 3 by avibootz

Related questions

...