238. Product of Array Except Self
func productExceptSelf(nums []int) []int {
length := len(nums)
resultArr := make([]int, length)
// Initialize the result array with 1's because 1 is the neutral element for multiplication.
for i := range resultArr {
resultArr[i] = 1
}
// Accumulate the left products
leftProduct := 1
for i := 0; i < length; i++ {
resultArr[i] = leftProduct
leftProduct *= nums[i]
}
// Accumulate the right products directly into the result array
rightProduct := 1
for i := length - 1; i >= 0; i-- {
resultArr[i] *= rightProduct
rightProduct *= nums[i]
}
return resultArr
}
Time Complexity
Since these loops are sequential and not nested, the overall time complexity is the sum of their complexities. However, since each loop is O(n), the total time complexity remains O(n).
领英推荐
Space Complexity
Considering the output array as part of the space requirement, the total space complexity is O(n). However, if we consider the output space not part of the auxiliary space complexity (as is common in many complexity analyses since the output does not count towards the "extra" space used by the algorithm), then the auxiliary space complexity would be O(1), indicating that the function uses constant extra space aside from the space needed for the output.