Solve LeetCode 238: Product of Array Except Self in Python with a prefix and suffix products approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Array / String |
| Reusable pattern | prefix and suffix products |
| Complexity | O(n) time and O(1) extra space excluding the output |
What the problem is testing
Write prefix products into the answer, then multiply by a running suffix product in a reverse pass.
Algorithm
- Write prefix products into the answer, then multiply by a running suffix product in a reverse pass.
- Maintain this invariant: Before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def productExceptSelf(self, nums):
answer = [1] * len(nums)
prefix = 1
for i, value in enumerate(nums):
answer[i] = prefix
prefix *= value
suffix = 1
for i in range(len(nums) - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answerWhy this is correct
The proof follows the maintained state: Before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(n) time and O(1) extra space excluding the output. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
The method naturally handles one or multiple zeros without division.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 380. Insert Delete GetRandom O(1) · Next: 134. Gas Station