Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements of nums except nums[i]. You must write an algorithm that runs in O(n) time and without using the division operation.
nums = [1,2,3,4][24,12,8,6]nums = [-1,1,0,-3,3][0,0,9,0,0]prefix[]: prefix[0]=1, then prefix[i]=prefix[i−1]×nums[i−1] (L→R)suffix[] with running product (R→L); set final[i]=prefix[i]×suffix[i]final[] — same as in-place ans[] trick, shown as 4 arrays for clarityAt index i, exclude nums[i] and multiply everything else: left part × right part. prefix[i] stores the left product, suffix[i] the right product, and final[i] is their product. The code reuses one array instead of three — we show all four rows so each piece is visible.
Multiplying everything and dividing breaks on zeros, and division is not allowed anyway. Recomputing the product for every index is O(n²).
Split it in two: the product of everything on the left, times the product of everything on the right. Build the left products in one pass, and multiply in the right products in a second pass.
Product except self equals left product times right product. Two passes, and the answer array doubles as storage.
Run the animation above on your own input, or watch the 1:37 video explanation of Product of Array Except Self with a dry run and Java code.