Product of Array except self
Problem Statement
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. Try solving it without using the division operation /
1. Using Division operation (violating instructions)
Cases to observe
- Two or more zero elements: All products will be zero
- One zero element: All products will be zero except at the zero element’s position
- No zero elements: The product at each postition will be combined product of all elements divided by current element (we’ll use the division operator)
C++ code
Metric | Complexity |
---|---|
Time | \( O(N) \) … 3 traversals at worst |
Space | \( O(1) \) |
2. Maintain Prefix and Suffix product arrays
Product of all elements except self means product of elements to it’s left multiplied by the product of elements to it’s right
- The first element of prefix array and last element of suffix array will be
1
(as their prefix and suffix are nothing i.e. empty arrays). So,prefix[0] = 1 = suffix[n-1]
. - The remaining values are calucated during traversals as:
prefix[i] = prefix[i-1] * nums[i-1]
suffix[i] = suffix[i+1] * nums[i+1]
Metric | Complexity |
---|---|
Time | \( O(N) \) … 3 traversals |
Space | \( O(N) \) … Extra space for prefix[] , suffix[] |
C++ code
Optimization: The multiplications can be done in-place right within the answer array
Metric | Complexity |
---|---|
Time | \( O(N) \) … 2 traversals |
Space | \( O(1) \) … Only ans[] , no extra space |