Product of Array Except Self — LeetCode 238 Python Solution
- Problem
- #238
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{nums} |
| Space | O(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.