Problem
Given an integer array
nums
, return an arrayanswer
such thatanswer[i]
is equal to the product of all the elements ofnums
exceptnums[i]
. The product of any prefix or suffix ofnums
is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs inO(n)
time and without using the division operation.
The hard part of this is the restriction and the no division operation rule.
Prefix-Postfix Solution
Do two passes through nums
. On the first pass, store the product of the elements before a given index in that index (prefix). On the second pass, store the product of the elements after a given index in that index (postfix), and multiply by the prefix. Give default values of for the left-most and right-most element for their prefix/postfix respectively.
Notes:
- Backwards for loop syntax for “
for i in range(len(nums)-1, -1 , -1):
” Basically, therange()
function generates a sequence of numbers and can take 1, 2, or 3 arguments:- 1 argument:
range(stop)
- Goes from 0 to
stop
- Goes from 0 to
- 2 arguments:
range(start, stop)
- Goes from
start
tostop
- Goes from
- 3 arguments:
range(start, stop, step)
- Goes from
start
tostop
, incrementing bystep
- Goes from
start
is inclusive butstop
is exclusive. Sorange(len(nums)-1, -1 ,-1)
is going from the last index to index0
(since index-1
is excluded) and decrementing by -1 every time. - 1 argument: