238. Product of Array Except Self ๐
Difficulty: Medium
- Tags: Array
, Prefix Sum
Description
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]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Examples
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Solution ๐ก
We can solve this problem using two passes through the array:
First pass calculates the prefix product for each element.
Second pass calculates the suffix product and multiplies it with the prefix product to get the final result.
Why not use division to calculate the product?
A straightforward approach would be to compute the total product of all the elements and then for each index, divide the total product by nums[i]
to get answer[i]
. However, this solution cannot be used because:
The problem explicitly prohibits using the division operation.
Division does not handle cases where the array contains zero, as division by zero is undefined.
Java
Time Complexity โณ
Both passes through the array take O(n), where
n
is the number of elements innums
.
Space Complexity ๐พ
The space complexity is O(1) for the output array
result
, as the calculation is done in-place.
You can find the full Solution.java
file here.
Last updated