Return an array where each position contains the product of all elements except the one at that position.
Given an integer array nums, build a new array answer such that answer[i] is the product of every value in nums except nums[i].
Do this without using division, and aim for linear time.
The array may contain zeroes, so your approach should handle them correctly.
Input Format
- A single integer array
nums. nums.length = n.- Each element is an integer.
Output Format
- Return an integer array
answerof lengthn. answer[i]should equal the product of all elements innumsexceptnums[i].
Constraints
- Use an approach that runs in time.
- Extra space beyond the output array should be kept minimal.
- Division is not allowed.
- Handle arrays containing zero values.
Example 1
Input
nums = [1,2,3,4]
Output
[24,12,8,6]
Explanation
For each position, multiply all numbers except the one at that index: 2×3×4 = 24, 1×3×4 = 12, 1×2×4 = 8, and 1×2×3 = 6.
Example 2
Input
nums = [-1,1,0,-3,3]
Output
[0,0,9,0,0]
Explanation
Every position except index 2 includes the zero, so the product is 0. At index 2, the product of the remaining values is (-1)×1×(-3)×3 = 9.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.