Problem 16
Product of Array Except Self
Medium · 20 pts · Array, Prefix Sum
Problem
You are given an array of N integers. Build a new array where the element at position i is the product of every element of the input except the one at position i, and print it. Do not use division: the array can contain zeros, so dividing the total product by each element does not work. Instead compute, for each position, the product of everything to its left (a prefix product) and everything to its right (a suffix product), and multiply the two. The values are small enough that every answer fits in a 64-bit integer.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the resulting array as space-separated integers.
Constraints
2 <= N <= 100000; -30 <= array[i] <= 30
Example input
4 1 2 3 4
Example output
24 12 8 6
Explanation
For 1 2 3 4: position 0 gets 2 × 3 × 4 = 24, position 1 gets 1 × 3 × 4 = 12, position 2 gets 1 × 2 × 4 = 8, and position 3 gets 1 × 2 × 3 = 6. The answer is 24 12 8 6.