Skip to content

Commit

Permalink
Merge pull request neetcode-gh#626 from LordKaT/main
Browse files Browse the repository at this point in the history
Update 238-Product-of-Array-Except-Self.java
  • Loading branch information
Ahmad-A0 authored Aug 29, 2022
2 parents 91e7255 + 27dddb9 commit 35c96b2
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions java/238-Product-of-Array-Except-Self.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,31 @@
//In first pass calculate the left product except self and in second calculate the right

class Solution {
public int[] productExceptSelf(int[] nums) {
int[] arr = new int[nums.length];
int right = 1, left = 1;
for (int i = 0; i < nums.length; i++) {
arr[i] = left;
left *= nums[i];
}
for (int i = nums.length - 1; i >= 0; i--) {
arr[i] *= right;
right *= nums[i];
}
return arr;
}

public int[] productExceptSelf(int[] nums) {
int[] arr = new int[nums.length];
int right=1, left=1;
for (int i = 0; i < nums.length; i++) {
arr[i] = left;
left *= nums[i];
}
for(int i = nums.length - 1; i >= 0; i--) {
arr[i] *= right;
right *= nums[i];
}
return arr;
}
public int[] productExceptSelfNumsAsPrefix(int[] nums) {
int[] output = new int[nums.length];
output[0] = 1;

for (int i = 0; i < nums.length - 1; i++)
output[i + 1] = output[i] * nums[i];

for (int i = nums.length - 2; i >= 0; i--) {
output[i] = nums[i + 1] * output[i];
nums[i] = nums[i] * nums[i + 1];
}
return output;
}
}

0 comments on commit 35c96b2

Please sign in to comment.