@codewithjonam

Leetcode

Mastering Code, One Challenge at a Time

238. Product of Array Except Self | JavaScript | Leetcode

June 20, 2024
Problem
Given an integer array
nums
, return an array
answer
such that
answer[i]
is equal to the product of all the elements of nums except
nums[i]
. You must write an algorithm that runs in
O(n)
time and without using the division operation. The output array does not count as extra space for space complexity analysis.

Example
Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]


Use nested
for
loops.
  • The first (outer) loop iterates through the
    nums
    array
  • The second (inner) loop iterates over
    nums
    array again and calculates the product of all elements except the current element (index) from the first loop
1/**
2 * @param {number[]} nums
3 * @return {number[]}
4 */
5var productExceptSelf = function (nums) {
6  const res = new Array(nums.length)
7
8  for (let i = 0; i < nums.length; i++) {
9    let product = 1
10    for (let j = 0; j < nums.length; j++) {
11      if (i !== j) {
12        product = product * nums[j]
13      }
14      res[i] = product
15    }
16  }
17
18  return res
19};
Time Complexity:
O(n2)

Space Complexity:
O(1)


Since the question specifically says the algorithm should run on
O(n)
time, this is not a valid solution.
Leetcode