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]. You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Explanation: For each index, multiply everything else: 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 product except the one at index 2 includes the 0, so they are all 0. At index 2 the product is -1 × 1 × -3 × 3 = 9.
Example 3
Input: nums = [0,0]
Output: [0,0]
Explanation: Each position's product is the other element, which is 0.
We can avoid the two helper arrays by writing prefix products directly into the output, then folding in the suffix product with a single backward pass.
Run checks all cases above. Submit evaluates all test cases.