Product of Array Except Self
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
For each position return the product of all the other numbers, without using division.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1The answer at a position = (product of everything to its left) x (product of everything to its right).
- Hint 2Can you build the left products in one walk and the right products in a second walk?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Houses in a row each have a discount factor. For house number 3 you want the combined effect of every OTHER house. Send a runner from the left who writes on each door "the product of everyone before you". Then send a runner from the right who multiplies each door by "the product of everyone after you". Now every door shows the product of all the others.
- The obvious way
For each position multiply all the others: O(n²). Dividing the total by the number fails with zeros and is not allowed.
- The key insight
Walk left to right writing, at each position, the product of everything before it (carrying a running product). Walk right to left multiplying each position by the product of everything after it (another running product). No division and no extra lists.
- The algorithm
- Make the answer list, all ones. Start a running product at 1.
- Walk left to right: write the running product into the answer, then multiply the running product by the current number.
- Reset the running product to 1. Walk right to left: multiply the answer by the running product, then update the running product the same way.
Watch it run
Examplenumbers = [1, 2, 3, 4]
Left walk: each door gets the product of everyone before it (the first door has nobody before it: 1).
left products: [1, 1, 2, 6]
Where people slip
- Update the running product AFTER using it, otherwise a number multiplies into its own answer.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def product_except_self(nums):
answer = [1] * len(nums)
running = 1
for position in range(len(nums)): # left to right
answer[position] = running # product of everyone before
running *= nums[position]
running = 1
for position in range(len(nums) - 1, -1, -1): # right to left
answer[position] *= running # times everyone after
running *= nums[position]
return answerNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.