Why it works
- The product of all numbers except nums[i] is the product of everything left of i times the product of everything right of i. The first pass leaves the left part in answer[i], the second multiplies in the right part.
- answer[i] is written before nums[i] joins left or right, so a number never gets into its own product. That is how the 0 gets 24.
- Division would not work here anyway: the product of everything is 0, and 0 / 0 says nothing. The two passes never divide, so a 0 is just another number.
Complexity
Time O(n): two passes. Memory O(1) besides the answer itself: left and right are single numbers.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗