Monday, August 24, 2015

Leetcode: Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
Understand the problem:
Note that the problem does not allow to use division and the time complexity should be in O(n). 

One solution is to maintain to arrays, to maintain the product before a[i] and after a[i]. 
i.e, for a[i], we have product of a[0] * a[1] * ... * a[i - 1], and a[n - 1] * ... * a[i + 1]. 
Therefore we can iterate the nums array forward and backward order, respectively.  
And for result[i] = before[i] * after[i].

Code (Java):
public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length < 2) {
            return new int[0];
        }
        
        int len = nums.length;
        int[] result = new int[len];
        int[] before = new int[len];
        int[] after = new int[len];
        
        before[0] = 1;
        for (int i = 1; i < len; i++) {
            before[i] = before[i - 1] * nums[i - 1];
        }
        
        after[len - 1] = 1;
        for (int i = len - 2; i >= 0; i--) {
            after[i] = after[i + 1] * nums[i + 1];
        }
        
        for (int i = 0; i < len; i++) {
            result[i] = before[i] * after[i];
        }
        
        return result;
    }
}

A constant space solution:
Note the the previous solution requires O(n) space cost. Can we solve the problem by only using constant space? The answer is yes. 

The idea is still the same. The only difference is we do the in-place. First of all, we iterate the nums array in forward and update the partial result. Then iterate the nums array again backward the update the final result. Instead of maintaining a after array, we only need one variable to maintain the after_i. 

Code (Java):
public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length < 2) {
            return new int[0];
        }
        
        int[] result = new int[nums.length];
        result[0] = 1;
        
        // before a[i]
        for (int i = 1; i < nums.length; i++) {
            result[i] = result[i - 1] * nums[i - 1];
        }
        
        // after a[i]
        int after = 1;
        for (int i = nums.length - 2; i >= 0; i--) {
            result[i] *= after * nums[i + 1];
            after *= nums[i + 1];
        }
        
        return result;
    }
}

1 comment:

  1. Your second solution has the same space complexity as first one as 2*O(n)~O(n).

    ReplyDelete