Problem:
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.)
Analysis:
This problem is very good! It involves the test against coding skills and simple dynamic programming! Basic idea: Since we were asked to compute the "product of whole array except self", and we were not allowed to use division. The instant idea is to: -------------------------------------------------- right product exclude i * left product exclude i --------------------------------------------------- Apparently, we need two arrays for those information. And we were only allowed to use constant space. We have to take advantage of the "nums array" and "res array". To take advantage of existing array, you must be very careful with direction and order. Otherwise you would mess up all existing information. For this problem, I use "res array" for left-to-right direction. for (int i = 1; i < len; i++) res[i] = nums[i] * res[i-1]; "nums array" for right to left direction. for (int i = len - 2; i >= 0; i--) nums[i] = nums[i+1] * nums[i]; Since the "right to left" computation would overwrite "nums array", the "res array" must be calculated firstly. When left and right array is ready, we could calculate the final result. int left = ((i == 0) ? 1 : res[i-1]); int right = ((i == len - 1) ? 1 : nums[i+1]); res[i] = left * right; *************************** Note: since when calculate res[i](overall product), we need to use res[i-1] (left product) information. We must caculate the res array through right to left!!!!
Solution:
public class Solution { public int[] productExceptSelf(int[] nums) { if (nums == null) throw new IllegalArgumentException("the passed in reference in null!"); if (nums.length == 0) return nums; int len = nums.length; int[] res = new int[len]; res[0] = nums[0]; //from left to right for (int i = 1; i < len; i++) res[i] = nums[i] * res[i-1]; //from right to left for (int i = len - 2; i >= 0; i--) nums[i] = nums[i+1] * nums[i]; for (int i = len - 1; i >= 0; i--) { int left = ((i == 0) ? 1 : res[i-1]); int right = ((i == len - 1) ? 1 : nums[i+1]); res[i] = left * right; } return res; } }