Leetcode: Product of Array Except Self

This question is EXTREMELY common at Facebook, Amazon, Apple, and Asana. 

Given an integer array nums, return an array answer such that the answer[i] is equal to the product of all the elements of nums except nums[i]. This would be O(n^2), would this be a reason? This is inefficient since the arrays can become much, much larger. How do we have an effective way to do this? We want the product to be guaranteed to fit a 32-bit integer. We can take the product of all the elements and divide but we are not allowed to use the division operation, which makes solving this problem much, much harder. 

We first figure out the multiplication of all of the elements on the left. Then we go to the right. We create an array of both the left multipliers and right multipliers and finally, multiply this to create the final array. Here is a visualization. 




And the corresponding code: 

class Solution {

    public int[] productExceptSelf(int[] nums) {

        int length = nums.length;

        int[] L = new int[length];

        int[] R = new int[length];

        int[] answer = new int[length];

        //leftmost element

        L[0] = 1;

        for(int i = 1; i < length; i++) {

            //product of element to left

            L[i] = nums[i - 1] * L[i - 1];

        }

        //rightmost element 

        R[length - 1] = 1;

        for(int i = length - 2; i >= 0; i--) {

            //product of element to right

            R[i] = nums[i + 1] * R[i + 1];

        }

        for(int i = 0; i < length; i++) {

            //totalproduct = left * right;

            answer[i] = L[i] * R[i];

        }

        return answer;

    }

}


To make this problem O(1), figure out to do this in place. 

Comments

Popular Posts