forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1.java
More file actions
65 lines (48 loc) · 1.52 KB
/
problem1.java
File metadata and controls
65 lines (48 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//We solve this using Prefix Product + Suffix Product without division.
//
//Steps:
//
//First pass (left → right):
//Store product of all elements to the left
//
//Second pass (right → left):
//Multiply product of all elements to the right
//
//This gives product except self.
//
// Time: O(n)
//Space: O(1) (excluding result array)
class Solution {
public int[] productExceptSelf(int[] nums) {
// Length of input array
int n = nums.length;
// Result array to store final answer
int[] result = new int[n];
// Running product variable (used for prefix and suffix)
int rp = 1;
// First element has no left elements
// So prefix product = 1
result[0] = 1;
// LEFT PASS
// Store product of all elements to the LEFT of current index
for(int i = 1; i < n; i++) {
// Multiply previous running product with previous element
rp = rp * nums[i - 1];
// Store prefix product
result[i] = rp;
}
// Reset running product for RIGHT PASS
rp = 1;
// RIGHT PASS
// Multiply result with product of elements to the RIGHT
for(int i = n - 2; i >= 0; i--) {
// Multiply running product with next element
rp = rp * nums[i + 1];
// Multiply prefix product (already stored)
// with suffix product
result[i] = result[i] * rp;
}
// Final result array
return result;
}
}