Facebook | Phone | Product of Array Except Self [Rejected]
Anonymous User
1656

https://leetcode.com/problems/product-of-array-except-self/

He challenge me that this is not O(1) space solution because I have new res array, he want inplace solution...Is it possible to solve this question by inplace ?

My solution:

  public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        // Calculate lefts and store in res.
        int left = 1;
        for (int i = 0; i < n; i++) {
            if (i > 0)
                left = left * nums[i - 1];
            res[i] = left;
        }
        // Calculate rights and the product from the end of the array.
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            if (i < n - 1)
                right = right * nums[i + 1];
            res[i] *= right;
        }
        return res;
    }
Comments (5)