mediumArraysPattern: Prefix Sum / Array Traversal
Array Product Exclusions Solution
Problem Statement
You are given an array of integers `numbers` where each element represents an asset price. Compute an array `result` such that for each index `i`, `result[i]` is the product of all numbers in the `numbers` array except for the one at index `i`. Return the `result` array.
Examples
Example 1:
Input:[1,2,3,4]
Output:[24,12,8,6]
Explanation: For the first element, the product of the rest is 2*3*4 = 24. For the second element, the product of the rest is 1*3*4 = 12. For the third element, the product of the rest is 1*2*4 = 8. For the fourth element, the product of the rest is 1*2*3 = 6.
Constraints
- 2 <= n <= 10^5
- -30 <= arr[i] <= 30
Time: O(N) Space: O(1)
Create answer array. First pass: store running prefix product into answer. Second pass: iterate backwards keeping a running suffix product, multiplying it into answer array. Time O(N), Space O(1) (excluding output array).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
