Educatifu
Open menu

Product of Array Except Self

Mediumarraysprefix-sums

For each position, output the product of all the other elements of the array — without using division.

Input

Line 1: an integer n. Line 2: n integers.

Output

n integers where the i-th is the product of every element except the i-th, space-separated.

Examples

Example 1

Input
4
1 2 3 4
Output
24 12 8 6

e.g. position 0 = 2·3·4 = 24.

Example 2

Input
3
2 3 4
Output
12 8 6

12, 8, 6.

Example 3

Input
3
-1 1 0
Output
0 0 -1

The zero makes two entries 0; the last is (-1)·1 = -1.

Constraints

  • 1 <= n <= 10^5
  • The overall products fit in 64-bit for the given tests.

Hints

Reveal hint 1

The answer at i is (product of everything to the left of i) × (product of everything to the right of i).

Reveal hint 2

Compute a running prefix product left-to-right, then a running suffix product right-to-left.

Reference solution (spoiler — try it yourself first)

Approach

Two passes: fill result[i] with the prefix product before i, then multiply by the suffix product after i. No division, handles zeros correctly.

import sys
d = list(map(int, sys.stdin.read().split()))
n = d[0]
a = d[1:1 + n]
res = [1] * n
pre = 1
for i in range(n):
    res[i] = pre
    pre *= a[i]
suf = 1
for i in range(n - 1, -1, -1):
    res[i] *= suf
    suf *= a[i]
print(' '.join(map(str, res)))

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation