Product of Array Except Self
Given an integer array, return an array where each element is the product of all other elements except itself. You must solve it without division and in O(n) time.
Write a function that returns an array where answer[i] is equal to the product of all elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operator.
How to Solve
Use two passes: first pass calculates left products (product of all elements to the left), second pass calculates right products (product of all elements to the right) and multiplies with left products. This avoids division and achieves O(n) time.
Code
Test Cases
Input 1
Expected Output: [24, 12, 8, 6] (24 = 234, 12 = 134, 8 = 124, 6 = 123)
Input 2
Expected Output: [0, 0, 9, 0, 0]
Input 3
Expected Output: [3, 2]
Complexity
Time Complexity: O(n) - Two passes through the array, each taking O(n) time.
Space Complexity: O(1) - Output array doesn't count as extra space. We only use a few variables for the right product calculation.