LeetCode – Product of Array Except Self (Java)

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].

Java Solution 1

public int[] productExceptSelf(int[] nums) {
    int[] result = new int[nums.length];
 
    int[] t1 = new int[nums.length];
    int[] t2 = new int[nums.length];
 
    t1[0]=1;
    t2[nums.length-1]=1;
 
    //scan from left to right
    for(int i=0; i<nums.length-1; i++){
        t1[i+1] = nums[i] * t1[i];
    }
 
    //scan from right to left
    for(int i=nums.length-1; i>0; i--){
        t2[i-1] = t2[i] * nums[i];
    }
 
    //multiply
    for(int i=0; i<nums.length; i++){
        result[i] = t1[i] * t2[i];
    }
 
    return result;
}

Java Solution 2

Space is O(1).

public int[] productExceptSelf(int[] nums) {
    int[] result = new int[nums.length];
 
    result[nums.length-1]=1;
    for(int i=nums.length-2; i>=0; i--){
        result[i]=result[i+1]*nums[i+1];
    }
 
    int left=1;
    for(int i=0; i<nums.length; i++){
        result[i]=result[i]*left;
        left = left*nums[i];
    }
 
    return result;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. srj_michael on 2015-9-5

    Simple solution without using extra space

    import java.util.*;
    import java.io.*;
    public class Product_of_Array_except_Self {
    public static void main(String args[])throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(System.out, true);
    int arr[]=new int[5];
    pw.println(“Enter 5 element of array”);
    for(int i=0;i<5;i++)
    {
    arr[i]=Integer.parseInt(br.readLine());
    }
    int product=1;
    for(int i=0;i<5;i++)
    {
    product=product*arr[i];
    }

    for(int i=0;i<5;i++)
    {
    int temp=arr[i];
    arr[i]=product/temp;
    }

    pw.println(Arrays.toString(arr));
    }
    }

  2. Shreyas Hirday on 2015-11-17

    it says to do it without division

  3. RMFOREVER123 on 2016-1-22

    Second solution is wrong. The second loop in the second program should start from i=1 and not i=0. result[0] is already determined.

  4. Jangku on 2016-5-29

    Why space O(1) for 2nd solution. It should be O(n) for result

  5. Rishabh Jain on 2017-2-4

    Space required is the input and output space. In this case that is the result and the nums array. Unlike the first solution where we were taking O(n) space for right and left arrays, we are declaring only constants in the second solution.

  6. Hooman on 2017-4-10

    still you are creating `n` new objects: int[] result = new int[nums.length];

Leave a comment

*