Sign inEnroll free
DSA Visualizer · 25 visualizationsProduct of Array Except Self
MediumArrays & Hashing

Product of Array Except Self

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 division and in O(n).

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(1)
def productExceptSelf(nums: list[int]) -> list[int]:
    n = len(nums)
    res = [1] * n
    prefix = 1
    for i in range(n):
        res[i] = prefix
        prefix *= nums[i]
    suffix = 1
    for i in range(n - 1, -1, -1):
        res[i] *= suffix
        suffix *= nums[i]
    return res
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough