PracticeNeetCode ↗LeetCode ↗
Given an integer array nums, return an array answer where answer[i] is the product of every element except nums[i] — without using division, in O(n) time.
answer[i] = (product of everything left of i) × (product of everything right of i) — division isn't needed if you compute both halves directly.result as an array of 1s, length n.result[i] = running prefix product so far, then multiply prefix by nums[i].result[i] by a running suffix product, then multiply suffix by nums[i].result — each slot now holds prefix × suffix, i.e. the product of everything except itself.Time: O(n) — Space: O(1) extra, excluding the output array
def productExceptSelf(nums: list[int]) -> list[int]:
n = len(nums)
result = [1] * n
prefix = 1
for i in range(n):
result[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return resultHow the solution above works, piece by piece.
result = [1] * n: the output array doubles as storage, so no extra arrays are needed.result[i] = prefix stores the product of everything before i, then prefix *= nums[i] includes nums[i] for the next index.result[i] *= suffix multiplies in the product of everything after i, then suffix *= nums[i].nums[i], and no division was used, so zeros in the input are handled.Running it on nums = [1, 2, 3, 4]: