Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem Link
https://leetcode.com/problems/product-of-array-except-self/description/
Solution
One immediate approach is to calculate the product of all elements in
nums
, and then divide this product by each element at indexi
to obtain the result.For example, if
nums
is[2,3,4]
, the total product is2 * 3 * 4 = 24
. Dividing this product by each element gives[24/2, 24/3, 24/4] = [12, 8, 6]
.This solution operates in O(n) time complexity, but division is not allowed in this problem.
Therefore, another approach can be considered.
In this approach, for each index
i
innums
, we calculate the product of all elements beforei
(from 0 toi-1
) and the product of all elements afteri
(fromi+1
to the end).Finally, we multiply these two products together to get the desired result, which is the product of all elements expect for
nums[i]
.