Prefix Product Array - Problem
Given an array of integers nums, build and return a new array result where each element result[i] is equal to the product of all elements that appear before index i in the original array.
For the first element (index 0), since there are no elements before it, the result should be 1.
Special handling for zeros: If there are zeros in the input array, handle them correctly by treating them as actual zero values in the multiplication.
Example: For array [2, 3, 4, 5], the result would be [1, 2, 6, 24] because:
result[0] = 1(no elements before index 0)result[1] = 2(product of elements before index 1)result[2] = 2 × 3 = 6(product of elements before index 2)result[3] = 2 × 3 × 4 = 24(product of elements before index 3)
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,3,4,5]
›
Output:
[1,2,6,24]
💡 Note:
result[0]=1 (no elements before), result[1]=2, result[2]=2×3=6, result[3]=2×3×4=24
Example 2 — With Zero
$
Input:
nums = [1,0,3,4]
›
Output:
[1,1,0,0]
💡 Note:
result[0]=1, result[1]=1, result[2]=1×0=0, result[3]=1×0×3=0
Example 3 — Small Array
$
Input:
nums = [5,2]
›
Output:
[1,5]
💡 Note:
result[0]=1 (no elements before), result[1]=5 (product of elements before index 1)
Constraints
- 2 ≤ nums.length ≤ 104
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code