Product of Array Except Self

Medium

Description

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. You must write an algorithm that runs in O(n) time and without using the division operation.

Examples

Input:nums = [1,2,3,4]
Output:[24,12,8,6]
Explanation:

For index 0: 2*3*4=24, index 1: 1*3*4=12, index 2: 1*2*4=8, index 3: 1*2*3=6.

Input:nums = [-1,1,0,-3,3]
Output:[0,0,9,0,0]
Explanation:

The product includes zero in most positions.

Input:nums = [2, -3, 4, -1]
Output:[12, -8, 6, -24]
Explanation:

For index 0: (-3)*4*(-1)=12, index 1: 2*4*(-1)=-8, index 2: 2*(-3)*(-1)=6, index 3: 2*(-3)*4=-24. This example demonstrates handling multiple negative numbers where the sign of each result depends on whether an odd or even number of negative values are multiplied.

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!