NeetCode #102LC-238MediumArrays & HashingBlind 75NC 150NC 250
← Back to All Problems#102 · #238 · Product of Array Except Self(除自身以外数组的乘积)
📌 Problem Statement & Constraints
Given an integer array
nums, return an array answer where answer[i] is the product of all elements of nums except nums[i]. Constraints: 2 <= nums.length <= 10^5, -30 <= nums[i] <= 30. The product of any prefix or suffix fits in a 32-bit integer. You must solve it in O(n) time and without using division.💡 Core Algorithmic Approaches
- Division is banned precisely because it breaks on zeros: with one zero every other position is 0 and the zero position is the product of the rest; with two or more zeros everything is 0. Special-casing that is error-prone.
- Instead, split the product into a prefix part and a suffix part:
answer[i] = (nums[0]*...*nums[i-1]) * (nums[i+1]*...*nums[n-1]). - Pass 1 (left to right): write the running prefix product into
answer[i]. - Pass 2 (right to left): keep a running suffix product and multiply it into
answer[i]. This needs only one output array, so extra space is O(1).
💻 Benchmark Python3 Implementation
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n
# Pass 1: answer[i] = product of everything strictly to the left of i
prefix = 1
for i in range(n):
answer[i] = prefix
prefix *= nums[i]
# Pass 2: multiply in the product of everything strictly to the right
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): exactly two linear passes, with constant work per element.
💾 Space Complexity
O(1) extra space beyond the output array. A naive two-array solution (separate prefix and suffix arrays) would use O(n) extra.
⚠️ Interview Pitfalls & Follow-ups
- Using division with a zero-count special case: it works, but the branches multiply and it is easy to get the two-zero case wrong. Interviewers usually prefer the prefix/suffix decomposition.
- Forgetting that the output array does not count toward space complexity: LeetCode's follow-up explicitly allows O(1) extra space excluding the answer.
- Initialising the prefix/suffix accumulators to 0: they must start at 1, the multiplicative identity.
- Overwriting
numsin place: it saves nothing here and destroys the input, which the follow-up question may forbid.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
除自身以外数组的乘积
给你一个整数数组 nums,返回数组 answer,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。题目数据保证数组 nums 之中任意元素的全部前缀元素和后缀的乘积都在 32 位整数范围内。请 不要使用除法 ,且在 O(n) 时间复杂度内完成此题。进阶:你可以在 O(1) 的额外空间复杂度内完成这个题目吗?(出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
核心要点
- 禁止除法的原因 :若允许除法,答案就是「总乘积 / nums[i]」,但 nums 中的 0 会导致除零,且 0 的个数会影响结果,需要特判,反而更复杂。
- 前缀积 × 后缀积 :answer[i] = (nums[0..i-1] 的乘积) × (nums[i+1..n-1] 的乘积)。分别预处理前缀积数组与后缀积数组,再相乘,时间 O(n)、空间 O(n)。
- 空间优化到 O(1)(关键) :先从左往右扫一遍,把前缀积直接写进 answer[i];再从右往左扫一遍,用一个变量 suffix 滚动维护后缀积,边扫边把 answer[i] *= suffix 。
- 为什么这样就省掉了两个辅助数组 :前缀积被「就地」存在输出数组里,后缀积只用了一个滚动变量,因此除输出数组外无额外空间。
常见陷阱
- 忘记处理 0 :本解法天然正确处理 0(0 会被当作普通乘数),但若改用「总乘积除法」的思路就会除零。面试中主动说明「本解无需特判 0」是加分点。
- 前缀积的初始化顺序写反 :必须先 answer[i] = prefix 再 prefix *= nums[i] ;若顺序颠倒,answer[i] 会把 nums[i] 自己也乘进去,得到错误的「全乘积」。
- 整数溢出 :Python 整数无溢出,但在 Java/C++ 中需注意乘积可能超出 int,应使用 long。
- 误答空间复杂度为 O(n) :进阶要求明确指出输出数组不计入额外空间,答 O(n) 会被认为没有理解题意。
参考实现
class Solution:
def productExceptSelf(self, nums: list[int]) -> list[int]:
n = len(nums)
answer = [1] * n
# 第一遍:answer[i] = nums[0..i-1] 的乘积(前缀积)
prefix = 1
for i in range(n):
answer[i] = prefix
prefix *= nums[i]
# 第二遍:从右往左乘上后缀积
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer