MediumNo. 0238

Product of Array Except Self — LeetCode 238 Python Solution

Pattern
Prefix Sum
Topics
Array, 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

PythonSolution
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

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

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

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.

Free to download. Check it runs on your machine, then pick a plan.