Product of Array Except Self
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
nums = [1,2,3,4][24,12,8,6]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.
nums = [-1,1,0,-3,3][0,0,9,0,0]The zero at index 2 makes most products zero. Only index 2's product ((-1)*1*(-3)*3=9) excludes the zero and is non-zero.
nums = [2, -3, 4, -1][12, -8, 6, -24]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 and sharpen your skills for technical interviews.