Product of array except self - using prefix and suffix products!
Select an index to see the calculation
Given an array, return an array where each element is the product of all other elements except itself.
Constraint: Don't use division! (What if there's a zero?)
prefix[i] = product of arr[0..i-1]
prefix[0] = 1 prefix[i] = prefix[i-1] × arr[i-1]
suffix[i] = product of arr[i+1..n-1]
suffix[n-1] = 1 suffix[i] = suffix[i+1] × arr[i+1]
result[i] = prefix[i] × suffix[i]
// No division needed! // O(n) time, O(n) space