Day 15 of 30 days Leetcode Challenge - Product of Array Except Self
Given an array nums of n
integers where n > 1
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n)
.
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
Solution
if we can use division, it's simple
Apply same technique asprefix sum
, we calculate bothprefix product
andsuffix product
, product ati
isprefix[i - 1] * suffix[i + 1]
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var prefix = Array(repeating: 1, count: nums.count)
var suffix = Array(repeating: 1, count: nums.count)
let lastIndex = nums.count - 1
prefix[0] = nums[0]
suffix[lastIndex] = nums[lastIndex]
for i in 1...lastIndex {
prefix[i] = prefix[i - 1] * nums[i]
suffix[lastIndex - i] = suffix[lastIndex - i + 1] * nums[lastIndex - i]
}
var res = [Int]()
res.append(suffix[1])
for i in 1..<nums.count-1 {
res.append(prefix[i-1] * suffix[i+1])
}
res.append(prefix[nums.count - 2])
return res
}
}
Constant space solution: updating...