loading...

Product of Array Except Self: time complexity O(n) vs O(n^2)

rajeshroyal profile image Rajesh Royal Originally published at rajeshroyal.com on ・2 min read

Problem – Product of Array Except Self

https://leetcode.com/problems/

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

**Input:** [1,2,3,4] **Output:** [24,12,8,6]

Constraint: It’s guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

Note: ** Please solve it **without division and in O(n).

Follow up:

Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

Group Anagrams ES6 solution

#1 O(n^2) time complexity solution

/\*\*@param {number[]} 
nums@return {number[]}\*/

var productExceptSelf = function(nums) {

   let result = [];
   result[nums.length - 1] = 1;

   for(let i = nums.length - 2; i >= 0; i--){
     result[i] = result[i + 1] * nums[i + 1];
   }

   let left = 1;
   for(let i = 0; i < nums.length; i++){
     result[i] = result[i] * left;
     left = left * nums[i];
   }

 return result;
};

runtime 140ms

#2 O(n) time complexity solution

/\*\*@param {number[]} 
nums@return {number[]}\*/

var productExceptSelf = function(nums) {
   let result = [];
   result[nums.length - 1] = 1;
   for(let i = nums.length - 2; i >= 0; i--){
     result[i] = result[i + 1] * nums[i + 1];
   }

   let left = 1;
   for(let i = 0; i < nums.length; i++){
     result[i] = result[i] * left;
     left = left * nums[i];
   }
   return result;
};

runtime 84ms

Submission Output on LeetCode:

Product of Array Except Self: time complexity O(n) vs O(n^2)

Posted on by:

rajeshroyal profile

Rajesh Royal

@rajeshroyal

Designer, Front-end Developer, Traveller, Hooper. I design and code beautifully simple things, and I love what I do.

Discussion

pic
Editor guide