Featured image of post 【Leetcode】python - [238] Product of Array Except Self 個人解法筆記

【Leetcode】python - [238] Product of Array Except Self 個人解法筆記

整理 LeetCode #238 Product of Array Except Self — 前後積、O(1)。

題目出處

238. Product of Array Except Self

難度

medium

題目分類

Array, Prefix Sum

2026-07-24 二刷

個人範例程式碼 - 二刷 (2026/07/24)

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        ans = [1] * len(nums)
        
        # forward
        prefix = 1
        for i in range(len(nums)):
            ans[i] *= prefix
            prefix *= nums[i]

        # backward
        suffix = 1
        for i in range(len(nums)-1, -1, -1):
            ans[i] *= suffix
            suffix *= nums[i]

        return ans

算法說明

藉由兩個 prefix, suffix 的 forward, backward 進行 array 掃過,
並用計算順序的時間差,可以先避開乘積,儲存答案。

Time Complexity

O(n)

Space Complexity

O(1) 只有使用兩個變數 prefix, suffix 協助解題

Boundary conditions

先後順序很重要,先處理 ans 避免污染,
當 ans 已經先處理好 (避開乘積),就可以更新 prefix, suffix

2022-06-04 一刷

個人範例程式碼 - 一刷 (2022/06/04)

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        result = [1 for _ in range(len(nums))]

        prefix_product = 1
        for i in range(len(nums)):
            result[i] *= prefix_product # first *= 1
            prefix_product *= nums[i]                        

        postfix_product = 1
        for i in range(len(nums)-1, -1, -1):
            result[i] *= postfix_product # first *= 1
            postfix_product *= nums[i]   

        return result

算法說明

這題要 O(n^2) 時間做出來非常容易,但題目先是希望要求 O(n) 時間算完,
既然都要求這樣的時間,我們勢必要做一些特殊的處理。

這裡我們用到類似 prefixSum 的概念 (我們用的是 prefixProduct)
因為仔細觀察,我們會發現答案就等於「前面積*後面積」,而數字分布是「前面積、(該數字)、後面積」,
因此我們可以簡單的用一個數字紀錄答案。

同時我們也可以實現「 O(1) 空間」的題目追加要求

【Leetcode】python - [238] Product of Array Except Self 個人解法筆記

input handling

如果沒有 nums, 回傳 [] (題目沒特別要求)

Boundary conditions

用兩次 for 迴圈控制範圍

Reference

Licensed under CC BY-NC-SA 4.0
最後更新 Jul 24, 2026
使用 Hugo 建立
主題 StackJimmy 設計