↓Skip to main content
  1. LeetCode/

LeetCode 238: Product of Array Except Self

·2 mins· ·
LeetCode Medium Array Prefix-Sum
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-27

  • Submissions: Runtime Error → Wrong Answer → Runtime Error → Wrong Answer → Output Limit Exceeded → Accepted → Runtime Error → Accepted ×5

Approach
#

res[i] = (nums[0] × ... × nums[i - 1]) × (nums[i + 1] × ... × nums[n - 1]), a prefix product times a suffix product (Prefix Sum with multiplication). The first pass stores the left product in res[i] (excluding nums[i]); the second pass, right to left, multiplies in the running right product. No division, so zeros need no special case.

My Attempts
#

  • The first 2022-10 version had a variable bug (UnboundLocalError).
  • The second wrote the reverse pass as range(len(nums), -1), an empty range, so no suffix product was applied; the prefix product was res[i - 1] * nums[i], including the element itself: [1, 3] returned [1, 3] instead of [3, 1].
  • With the range fixed the prefix still included the element, returning [3, 3]. Using nums[i - 1] was correct, but a leftover print caused Output Limit Exceeded until removed.

Solution
#

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

Complexity
#

Time O(n), space O(1) excluding the output.

Mistakes to Avoid
#

  • The prefix product excludes the element: res[i] = res[i - 1] * nums[i - 1], not nums[i].
  • A reverse loop is range(n - 1, -1, -1); range(n, -1) is empty.
  • Division is not allowed, and zeros may appear.

Interview Explanation
#

Each answer is the product of everything left of it times everything right of it. One pass stores the left products, a reverse pass multiplies in a running right product; no division and O(1) extra space.

Related

LeetCode 128: Longest Consecutive Sequence
·2 mins
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 note: put everything in a set and count upward only from values whose x - 1 is absent; each value is seen at most twice, O(n)
LeetCode 167: Two Sum II - Input Array Is Sorted
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search
LeetCode 167 note: sorted, so move two pointers inward, shifting right when the sum is too large and left when too small; indices are 1-based
LeetCode 347: Top K Frequent Elements
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 note: count first, then take the k most frequent with a size-k heap or a bucket sort indexed by count
LeetCode 75: Sort Colors
·2 mins
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 note: the Dutch flag, with 0s left of low and 2s right of high; after swapping a 2 to high, do not advance, since the swapped-in value is unchecked
LeetCode 78: Subsets
·1 min
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 78 note: each element is either taken or not; iteratively, each new number copies every existing subset with the number appended
LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts