Advertisement
Guest User

Grokking #200

a guest
Dec 6th, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.55 KB | None | 0 0
  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
Add Comment
Please, Sign In to add comment
Advertisement