Boss lesson · Unit 03
Product except self
A pass from the left, a pass from the right, no division
What you practise
- A prefix pass and a suffix pass, no division
Try a question from this lesson
Pick one
For each position you need the product of all the other numbers. Why not multiply everything together once and divide by the number at each position?
Correct answer
One zero in the list and the division breaks
Why
With a zero in the list the full product is 0, and at the zero itself you would compute 0 ÷ 0. The answer there should be the product of the others, which may not be 0 at all.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Boss: product of all the others
For each position, compute the product of all the OTHER numbers. [1, 2, 3, 4] becomes [24, 12, 8, 6].
The catch: no division, and it must run in O(n). The trick is the running-total idea, used once from each side.
Concept
Two passes
Pass one, left to right: store in out[i] the product of everything before index i.
Pass two, right to left: multiply each slot by the product of everything after it, kept in one running variable. No division, and no second array.
def except_self(nums):
n = len(nums)
out = [1] * n
for i in range(1, n):
out[i] = out[i - 1] * nums[i - 1]
right = 1
for i in range(n - 1, -1, -1):
out[i] *= right
right *= nums[i]
return outfunction exceptSelf(nums) {
const n = nums.length;
const out = new Array(n).fill(1);
for (let i = 1; i < n; i++) {
out[i] = out[i - 1] * nums[i - 1];
}
let right = 1;
for (let i = n - 1; i >= 0; i--) {
out[i] *= right;
right *= nums[i];
}
return out;
}function exceptSelf(nums: number[]) {
const n = nums.length;
const out = Array<number>(n).fill(1);
for (let i = 1; i < n; i++) {
out[i] = out[i - 1] * nums[i - 1];
}
let right = 1;
for (let i = n - 1; i >= 0; i--) {
out[i] *= right;
right *= nums[i];
}
return out;
}Python noterange(n - 1, -1, -1) counts down from the last index to 0. The stop value, -1, is excluded as always.
JavaScript notenew Array(n).fill(1) makes an array of n ones. Without fill, the slots would be empty holes.
TypeScript noteArray<number>(n) states the element type (new is optional for Array). The return type is not written: it is inferred as number[] from return out.
9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.