LeetCode 238: Product of Array Except Self — Python Solution

LeetCode 238: Product of Array Except Self is a Medium array / string problem. This Python walkthrough develops a prefix and suffix products solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patternprefix and suffix products
ComplexityO(n) time and O(1) extra space excluding the output

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, write prefix products into the answer, then multiply by a running suffix product in a reverse pass. The invariant worth writing beside the code is: Before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i.

Step-by-step algorithm

  1. Identify the input state consumed by productExceptSelf(nums) and initialize the data required by the prefix and suffix products pattern.
  2. Write prefix products into the answer, then multiply by a running suffix product in a reverse pass.
  3. After each update, verify the page’s central invariant: Before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i.
  4. Finish only after the boundary behavior is covered: The method naturally handles one or multiple zeros without division.

Python solution

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 answer

Reading the implementation

The main entry point is productExceptSelf(nums). The named working state includes answer, prefix, suffix; those variables make the prefix and suffix products state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, write prefix products into the answer, then multiply by a running suffix product in a reverse pass.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Write prefix products into the answer, then multiply by a running suffix product in a reverse pass. Each update records the current item without invalidating earlier decisions; consequently, before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(1) extra space excluding the output. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().productExceptSelf([1,2,3,4]) == [24,12,8,6]

Common mistakes and edge cases

  • Problem-specific boundary: The method naturally handles one or multiple zeros without division.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i.

Interview review checklist

  • Explain why prefix and suffix products matches the structure of this input.
  • State the invariant in one sentence before tracing code: Before the reverse pass reaches i, the answer holds the product left of i and suffix holds the product right of i.
  • Derive O(n) time and O(1) extra space excluding the output from how many times each element or state is visited.
  • Test the boundary explicitly: The method naturally handles one or multiple zeros without division.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 380. Insert Delete GetRandom O(1) · Next: 134. Gas Station