Problem Statement
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements of nums except nums[i].
You must solve it without using division and in O(n) time.
Approach
Use prefix and suffix products. First pass computes prefix products, second pass multiplies by suffix products.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(1) excluding output |
Examples
Example 1
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Constraints
- βΈ
2 <= nums.length <= 10^5 - βΈ
-30 <= nums[i] <= 30 - βΈThe product of any prefix or suffix fits in a 32-bit integer
Loading...
Sign in to run your code...
Asked by companies:
AmazonFacebookAppleMicrosoft