File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 238. Product of Array Except Self
3+ * Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
4+ * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
5+ * You must write an algorithm that runs in O(n) time and without using the division operation.
6+ *
7+ * https://leetcode.com/problems/product-of-array-except-self/description/
8+ */
9+
10+ // O(n) time
11+ // O(1) space
12+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
13+ const result = new Array ( nums . length ) . fill ( 1 ) ;
14+
15+ let left = 1 ;
16+ for ( let i = 0 ; i < nums . length - 1 ; i ++ ) {
17+ left *= nums [ i ] ;
18+ result [ i + 1 ] *= left ;
19+ }
20+
21+ let right = 1 ;
22+ for ( let i = nums . length - 1 ; i > 0 ; i -- ) {
23+ right *= nums [ i ] ;
24+ result [ i - 1 ] *= right ;
25+ }
26+
27+ return result ;
28+ }
You can’t perform that action at this time.
0 commit comments