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
INPUTALGORITHMRESULT23450123nums = [2,3,4,5]Find product of elementsbefore each position1Initialize running_product = 12For each position i:result[i] = running_productrunning_product *= nums[i]3Single pass through array4Time: O(n), Space: O(1)12624result = [1,2,6,24]Products of all elementsbefore each positionKey Insight:Maintain running product while iterating - no need to recalculate from scratcheach time. One pass gives optimal O(n) time complexity.TutorialsPoint - Prefix Product Array | Single Pass Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
32.5K Views
Medium Frequency
~15 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen