Skip to content

Commit 9788095

Browse files
author
Yi Gu
committed
[Array] add solution to Product of Array Except Self
1 parent b9395cc commit 9788095

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Array/ProductExceptSelf.swift

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/product-of-array-except-self/
3+
* Primary idea: Use two arrays to hold multiplication result from left and right sides
4+
* while iterating the original array
5+
* Time Complexity: O(n), Space Complexity: O(n)
6+
*/
7+
8+
class ProductExceptSelf {
9+
func productExceptSelf(nums: [Int]) -> [Int] {
10+
var res = [Int]()
11+
12+
guard nums.count > 0 else {
13+
return res
14+
}
15+
16+
let left = _initLeft(nums)
17+
let right = _initRight(nums)
18+
19+
for i in 0 ..< nums.count {
20+
res.append(left[i] * right[i])
21+
}
22+
23+
return res
24+
}
25+
26+
private func _initLeft(nums: [Int]) -> [Int] {
27+
var left = [Int]()
28+
left.append(1)
29+
30+
for i in 1 ..< nums.count {
31+
left.append(left[i - 1] * nums[i - 1])
32+
}
33+
34+
return left
35+
}
36+
37+
private func _initRight(nums: [Int]) -> [Int] {
38+
var right = Array(count: nums.count, repeatedValue: 1)
39+
40+
for i in (nums.count - 2).stride(through: 0, by: -1) {
41+
right[i] = right[i + 1] * nums[i + 1]
42+
}
43+
44+
return right
45+
}
46+
}

0 commit comments

Comments
 (0)