Product of Array Elements
Given an array A, generate an array B such that
The brute-force approach takes O(n^2) time.
One simple improvement would be pre-calculating the product of A[0], A[1] ... and A[n-1]. Then for each A[i], we can easily generate B[i] by dividing the total product by A[i]. We only need O(2n) in time.
A few corner cases need to be considered:
If divide operation is not allowed, we can still have a linear time solution. The idea is to generate two helper arrays, and then calculate B[i] based on these two arrays.
Follow-up: what if extra space is not allowed?
Actually there is a pretty neat solution which only need O(2n) in time and O(1) in space.
B[i] = A[0]*A[1]*...A[i-1]*A[i+1]*...A[n-1].
The brute-force approach takes O(n^2) time.
One simple improvement would be pre-calculating the product of A[0], A[1] ... and A[n-1]. Then for each A[i], we can easily generate B[i] by dividing the total product by A[i]. We only need O(2n) in time.
A few corner cases need to be considered:
- What if there is one zero in the array, i.e., A[i] = 0? The total product will be 0, and the divide operations are invalid. In this case, B[j] = 0 if j not equals to i, and B[i] is the only non-zero element in the array.
- What if there are more than 2 zeros in the array? The entire B should be 0.
If divide operation is not allowed, we can still have a linear time solution. The idea is to generate two helper arrays, and then calculate B[i] based on these two arrays.
Follow-up: what if extra space is not allowed?
Actually there is a pretty neat solution which only need O(2n) in time and O(1) in space.
Comments
Post a Comment