Easy java solution in O(n) time and no extra space(2ms)


  • 8
    R
    public class Solution {
    public int[] productExceptSelf(int[] nums) {
        final int[] result = new int[nums.length];
        for(int i=0, leftProduct=1; i<nums.length; i++) { // left product
            result[i] = leftProduct;
            leftProduct *= nums[i];
        }
        for(int i=nums.length-1, rightProduct=1; i>=0; i--) { // right product
            result[i] *= rightProduct;
            rightProduct *= nums[i];
        }
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.