Product of Array Except Self - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given an array nums, build an array result where result[i] equals the product of all elements in nums except nums[i], without using division.

Key Idea (Intuition)

For each index i, the answer is the product of all elements to its left times the product of all elements to its right. We can compute this in two linear passes using a single running product variable: first fill result[i] with the left product for each index, then traverse from right to left and multiply in the right product.

Initialization

  • Create result with length n.
  • Set product = 1 — a running product variable.
    It will represent the left product of the current index during the left-to-right traversal and the right product of the current index during the right-to-left traversal.

Traversal — Left to Right

For each index i from 0 to n-1:

  1. Write the current product into result[i] — this is the left product for index i.
  2. Update product by multiplying with nums[i] so it becomes the left product for the next index.

Traversal — Right to Left

Reset product = 1 and iterate i from n-1 down to 0: In this pass, product represents the right product for the current index.

  1. result[i] currently holds the left product for index i. Multiply it by the current product to factor in the right product.
  2. Update product by multiplying with nums[i] so it becomes the right product for the previous index in the next step.

Return

After both passes, result contains the product of all elements except self for each index. Return result.

Time Complexity

The algorithm makes two full passes over the array: one left-to-right and one right-to-left. Each step only involves constant-time operations (multiplication and assignment). Therefore, the time complexity is O(n), where n is the length of the input array.

Space Complexity

The algorithm uses only a constant amount of extra space for variables such as product and index, so the extra space complexity is O(1). However, we also allocate the result array to hold the output, which requires O(n) space. Thus overall, the algorithm uses O(1) extra space and O(n) space for the output.

Visucodize editorial solution titled JS Solution for LeetCode's Product of Array Except Self coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/product-of-array-except-self.