Skip to content

Commit

Permalink
Create 238-Product-of-Array-Except-Self.java
Browse files Browse the repository at this point in the history
  • Loading branch information
SharmaTushar1 authored Jul 6, 2022
1 parent c482529 commit 46c2c84
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions java/238-Product-of-Array-Except-Self.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//Just store the left and right product (Try doing this with extra space first)
//This one is constant space because we are returning the array we created

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

0 comments on commit 46c2c84

Please sign in to comment.