#C456. Product Except Self

    ID: 48111 Type: Default 1000ms 256MiB

Product Except Self

Product Except Self

Given an array of integers nums, your task is to return a new array where each element at index i is equal to the product of all the elements in nums except nums[i].

You must solve this problem without using division and with a time complexity of \(O(n)\). The solution is expected to handle edge cases, such as empty arrays or arrays containing one element.

Example:

  • Input: [1, 2, 3, 4]
  • Output: [24, 12, 8, 6]

For index 0: Product of elements except 1 is \(2 \times 3 \times 4 = 24\).
For index 1: Product of elements except 2 is \(1 \times 3 \times 4 = 12\).
For index 2: Product of elements except 3 is \(1 \times 2 \times 4 = 8\).
For index 3: Product of elements except 4 is \(1 \times 2 \times 3 = 6\).

inputFormat

The first line of input contains an integer \(n\) denoting the number of elements in the array. The second line contains \(n\) space-separated integers representing the array.

Note: \(n\) can be zero or one, and there may be negative values or zeros in the array.

outputFormat

Output a single line containing \(n\) space-separated integers, where each integer is the product of all the elements of the input array except the element at that index.

## sample
4
1 2 3 4
24 12 8 6