Prefix sum · Medium
A numerical report needs one product for every excluded array entry. Values can include zero, so dividing the full product is not valid. The report must keep the original array unchanged.
Return an array where output[i] is the product of all nums entries except nums[i] without using division.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "nums": number[] }.
Fields
- nums is an integer array. The product of no factors is defined as 1.
Output
Return value
- Return an equally sized array. For an empty input return []; for one entry return [1].
- Zeros and negative values follow normal multiplication. Do not use division or logarithmic approximation.
Constraints
- 0 <= nums.length <= 100000; values are integers in [-100,100].
- The product of all nonzero entries has magnitude at most Number.MAX_SAFE_INTEGER, so intermediate nonzero products are exact.
Examples
Example 1
{
"nums": [
1,
2,
3,
4
]
}Returns
[
24,
12,
8,
6
]Each position excludes its own factor.
Example 2
{
"nums": [
2,
0,
3
]
}Returns
[
0,
6,
0
]Only the zero position has a nonzero result.
Required complexity
O(n) time and O(1) working space excluding output