Skip to content

Commit aaf4e9b

Browse files
authored
Merge pull request neetcode-gh#27 from chandra9302/patch-4
Create 238-Product-of-array-except-self.swift
2 parents 7241279 + 1f4842c commit aaf4e9b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/product-of-array-except-self/
3+
*/
4+
5+
class ProductExceptSelf {
6+
func productExceptSelf(_ nums: [Int]) -> [Int] {
7+
var res = [Int](repeating: 1, count: nums.count)
8+
9+
var prefix = 1
10+
for i in 0..<nums.count {
11+
res[i] = prefix
12+
prefix *= nums[i]
13+
}
14+
var postfix = 1
15+
for i in stride(from: nums.count-1, to: -1, by: -1) {
16+
res[i] *= postfix
17+
postfix *= nums[i]
18+
}
19+
return res
20+
}
21+
}

0 commit comments

Comments
 (0)