Given a list of numbers, find for each position the product of all the other numbers. Division is not allowed, because the list can contain zeros.
What to build
A program that prints, for every position, the product of all numbers except the one at that position.
Requirements
- Do not use division.
- Use O(n) time: two passes, not a nested loop.
Input
The first line has n. The second line has the n integers.
Output
The n products, separated by spaces.
Constraints
1 ≤ n ≤ 20; each number from -10 to 10.
Example
Input:
4
1 2 3 4
Output:
24 12 8 6
Why it works
The product of the others is the product to the left times the product to the right. A forward pass stores the running product of everything before each position, and a backward pass multiplies in the running product of everything after it.
Examples
4 1 2 3 4
24 12 8 6
5 -1 1 0 -3 3
0 0 9 0 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Without division: the answer at i is (product of everything left of i) times (product of everything right of i).
Hint 2
Build the left products in one pass and multiply in the right products in a second pass from the end.
Hint 3
Zeros make division unsafe, which is why this problem forbids it.
Solution
Show one correct solution (try it yourself first)
n = int(input())
nums = list(map(int, input().split()))
out = [1] * n
left = 1
for i in range(n):
out[i] = left
left *= nums[i]
right = 1
for i in range(n - 1, -1, -1):
out[i] *= right
right *= nums[i]
print(*out)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step