Skip to content

Commit aecb6d2

Browse files
committed
Add Products Array Without Current Element
1 parent 286f855 commit aecb6d2

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun productArrayWithoutCurrentElement(nums: List<Int>): List<Int> {
2+
val n = nums.size
3+
val res = MutableList(n) { 1 }
4+
// Populate the output with the running left product.
5+
for (i in 1 until n) {
6+
res[i] = res[i - 1] * nums[i - 1]
7+
}
8+
// Multiply the output with the running right product, from right to
9+
// left.
10+
var rightProduct = 1
11+
for (i in n - 1 downTo 0) {
12+
res[i] *= rightProduct
13+
rightProduct *= nums[i]
14+
}
15+
return res
16+
}

0 commit comments

Comments
 (0)