Advertisement
Guest User

Grokking #200

a guest
Dec 6th, 2021
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2.   public int[] productExceptSelf(int[] nums) {
  3.    
  4.     int[] ans = new int[nums.length];
  5.     Arrays.fill(ans, 1);
  6.    
  7.     // calculate shifted left prefix product
  8.     for (int i = 1; i < nums.length; i++) {
  9.       ans[i] = ans[i - 1] * nums[i - 1];
  10.     }
  11.    
  12.     // calculate shifted right prefix product and answer
  13.     int rightProduct = 1;
  14.     for (int i = nums.length - 2; i >= 0; i--) {
  15.       rightProduct = rightProduct * nums[i + 1];
  16.      
  17.       ans[i] = ans[i] * rightProduct;            
  18.     }
  19.  
  20.     return ans;
  21.   }
  22. }
Advertisement
RAW Paste Data Copied
Advertisement