I was asked this question in a job interview, and I’d like to know how others would solve it. I’m most comfortable with Java, but solutions in other languages are welcome.
Given an array of numbers,
nums, return an array of numbersproducts, whereproducts[i]is the product of allnums[j], j != i.Input : [1, 2, 3, 4, 5] Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24]You must do this in
O(N)without using division.
An explanation of polygenelubricants method is:
The trick is to construct the arrays (in the case for 4 elements):
Both of which can be done in O(n) by starting at the left and right edges respectively.
Then, multiplying the two arrays element-by-element gives the required result.
My code would look something like this:
If you need the solution be O(1) in space as well, you can do this (which is less clear in my opinion):