Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vamsitallapudi/ee368d5821a57b6006a2abfb2d17e4f9 to your computer and use it in GitHub Desktop.
Save vamsitallapudi/ee368d5821a57b6006a2abfb2d17e4f9 to your computer and use it in GitHub Desktop.
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
Arrays.fill(ans, 1);
for(int i = 1; i< n; i++) {
ans[i] = ans[i-1] *nums[i-1]; // calculating prefix
}
int curr = 1;
for(int j = n-1; j>=0; j--) {
ans[j] *= curr; // multiplying by suffix
curr*=nums[j]; // updating curr with suffix for the next iteration
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment