Product of Array Except Self — LeetCode 238 Python Solution

MediumArrayPrefix Sum
Problem
#238
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Example

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

Python solution

Python
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [0] * n
        left = right = 1
        for i, x in enumerate(nums):
            ans[i] = left
            left *= x
        for i in range(n - 1, -1, -1):
            ans[i] *= right
            right *= nums[i]
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 238. Product of Array Except Self is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75, LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 238. Product of Array Except Self?
LeetCode 238. Product of Array Except Self is rated Medium on LeetCode.
What is the time complexity of LeetCode 238. Product of Array Except Self?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 238. Product of Array Except Self?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 238. Product of Array Except Self cover?
LeetCode 238. Product of Array Except Self is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview