sudopower

lc_238

LC: 238: Product of Array except self

Link to problem

Solution 1

func productExceptSelf(nums []int) []int {
    // seems hard, had to check solution, add to revision list
    // loop from one end and create a prefix-product like a prefix-sum
    // loop from other end do the same with the new array
    // it's a bit mathy difficult to explain, will need revision

    var output []int
    for _ = range nums {
        output=append(output,1)
    }

    ps:=1
    for i:=len(nums)-1;i>-1;i--{
        output[i]=output[i]*ps
        ps=ps*nums[i]
    }    
    
    ps=1
    for i:=0;i<len(nums);i++{
        output[i]=output[i]*ps
        ps=ps*nums[i]
    }

    return output

}

http://play.golang.org/p/duRF5gXJEP.go

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blogs