/*
Computes the product of the array except self.
nums = input array
returns a new array containing the result
*/
func productExceptSelf(_ nums: [Int]) -> [Int] {
let size = nums.count
var answer = Array(repeating: 1, count: size)
// ---- Prefix products ----
// answer[i] gets the product of all elements before i
var prefix = 1
for i in 0..<size {
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
var suffix = 1
for i in stride(from: size - 1, through: 0, by: -1) {
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
}
// Main program
let arr = [5, 2, 3, 4]
let result = productExceptSelf(arr)
print("Result:", terminator: " ")
for x in result {
print(x, terminator: " ")
}
/*
run:
Result: 24 60 40 30
*/