Return an array answer where answer[i] is the product of all elements of nums except nums[i], in O(n) time without using division.
Store prefix products in the output, then sweep right to left with a running suffix product.
1function productExceptSelf(nums: number[]): number[] {2const n = nums.length, out = new Array(n).fill(1);3for (let i = 1; i < n; i++) out[i] = out[i - 1] * nums[i - 1];4let suffix = 1;5for (let i = n - 1; i >= 0; i--) {6out[i] *= suffix;7suffix *= nums[i];8}9return out;10}
out starts as all 1s.
Space: play/pause · ←/→: step