#238MediumPrefix Sum

Product of Array Except Self

Build left and right product arrays without using division.

AmazonMicrosoftAppleLinkedInAdobe

Problem Statement

Given an integer array nums, return an array answer such that answer[i] equals the product of all elements of nums except nums[i]. You must write an algorithm that runs in O(n) time and without using the division operation.

Examples

Example 1

Input:nums = [1,2,3,4]
Output:[24,12,8,6]

Explanation: answer[0]=2×3×4=24, answer[1]=1×3×4=12...

Example 2

Input:nums = [-1,1,0,-3,3]
Output:[0,0,9,0,0]

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • No division allowed.

Solutions

1
Left & Right Pass (Two Extra Arrays)
TimeO(n)SpaceO(n)

Build a left[i] array where left[i] = product of all elements before i. Build a right[i] where right[i] = product of all elements after i. Answer[i] = left[i] * right[i].

Visual Animation
def productExceptSelf(nums: list[int]) -> list[int]:
    n = len(nums)
    left = [1] * n
    for i in range(1, n):
        left[i] = left[i-1] * nums[i-1]
    right = [1] * n
    for i in range(n-2, -1, -1):
        right[i] = right[i+1] * nums[i+1]
    return [left[i] * right[i] for i in range(n)]

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Prefix Sum to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems