NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 1480. Running Sum of 1d ArrayEasy
  • 1. Two SumEasy
  • 14. Longest Common PrefixEasy
  • 26. Remove Duplicates from Sorted ArrayEasy
  • 27. Remove ElementEasy

238. Product of Array Except Self

Medium
ArrayPrefix Sum
Companies:
AppleLinkedInAmazonFacebookMicrosoft
Answered: Apr 19, 2026
View on LeetCode

Problem Description

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in $O(n)$ time and without using the division operation.

Examples

Example 1

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints

  • 2 <= nums.length <= 105
  • -30 <= nums[i] <= 30
  • The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.

Follow-up

Can you solve the problem in $O(1)$ extra space complexity? (The output array does not count as extra space for space complexity analysis.)

💡 Hints (2)


Solutions

Complexity Analysis

Time Complexity:O(n2)

For each of the n elements, we iterate through all n elements again, resulting in O(n2)O(n^{2})O(n2) total operations.

Space Complexity:O(1)extraspace,O(n)fortheoutputarray.

No auxiliary data structures are used beyond the output array.

The brute force approach calculates the product for each index by iterating through all other elements in a nested loop. For each position i, we initialize a product of 1 and multiply every element nums[j] where j ≠ i, appending the result to the output array. While correct, this quadratic solution does not satisfy the problem's O(n)O(n)O(n) requirement.

Complexity Analysis

Time Complexity:O(n)

We make three linear passes — one to build prefix, one to build suffix, and one to compute the result — each O(n)O(n)O(n).

Space Complexity:O(n)

Two auxiliary arrays of size n (prefix and suffix) are allocated beyond the output array.

This approach precomputes two auxiliary arrays: prefix[i] holds the product of all elements before index i, and suffix[i] holds the product of all elements after index i. We fill prefix with a forward pass and suffix with a backward pass, then combine them so that result[i] = prefix[i] * suffix[i], giving the product of all elements except the one at i.

Complexity Analysis

Time Complexity:O(n)

Two linear passes are made over the array — one forward for prefix products and one backward for suffix products.

Space Complexity:O(1)extraspace,O(n)fortheoutputarray.

Only two scalar variables (prefix and suffix) are used beyond the output array.

This solution eliminates the two auxiliary arrays from Solution 2 by writing prefix products directly into the result array. In a forward pass, result[i] is set to the running prefix product before index i. In a backward pass, a running suffix variable is multiplied into each result[i], overlaying the suffix product on top of the already-stored prefix — achieving O(1)O(1)O(1) extra space.

Complexity Analysis

Time Complexity:O(n)

A single pass of n iterations covers the entire array, with O(1)O(1)O(1) work per iteration.

Space Complexity:O(1)extraspace,O(n)fortheoutputarray.

Only two scalar variables (prefix and suffix) are used beyond the output array.

This solution compresses Solution 3's two passes into a single loop by simultaneously updating the result from both ends of the array. In each iteration i, the front pointer multiplies the running prefix into result[i] while the back pointer multiplies the running suffix into result[n-1-i], interleaving the prefix and suffix accumulation in one traversal.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Brute Force
O(n2)O(n^{2})O(n2)O(1)O(1)O(1) extra spaceSimplest to understand; no extra data structures neededO(n2)O(n^{2})O(n2) time fails the problem's O(n)O(n)O(n) requirement
Prefix and Suffix Arrays
O(n)O(n)O(n)O(n)O(n)O(n)Clear, intuitive separation of prefix and suffix logic into two explicit arrays⚠️ Requires O(n)O(n)O(n) extra space for the two auxiliary arrays
Two-Pass Prefix & Suffix
O(n)O(n)O(n)O(1)O(1)O(1) extra spaceOptimal time and space; two clean, readable passes over the arrayRequires two passes instead of one
Single-Pass Prefix & Suffix
O(n)O(n)O(n)O(1)O(1)O(1) extra spaceSame optimal complexity as Solution 3 but completes in a single loopInterleaved bidirectional index updates reduce readability

The optimal approach for this problem is Solution 3: Two-Pass Prefix & Suffix, which achieves O(n)O(n)O(n) time complexity and O(1)O(1)O(1) extra space. It eliminates the auxiliary arrays of Solution 2 by writing prefix products directly into the result array and overlaying suffix products in a backward pass, satisfying both the O(n)O(n)O(n) time requirement and the O(1)O(1)O(1) space follow-up. Solutions marked with ⚠️ do not meet the follow-up requirement and are not recommended.


Previous232. Implement Queue using Stacks
Next242. Valid Anagram
Related posts
  • 1480. Running Sum of 1d ArrayEasy
  • 1. Two SumEasy
  • 14. Longest Common PrefixEasy
  • 26. Remove Duplicates from Sorted ArrayEasy
  • 27. Remove ElementEasy
On this page
16 lines
1class Solution:
2 def productExceptSelf(self, nums: List[int]) -> List[int]:
3 result = []
4
5 # Loop through each element in the input list
6 for i in range(len(nums)):
7 product = 1
8
9 # Loop through the list again to calculate the product of all elements except the current one
10 for j in range(len(nums)):
11 if i != j:
12 product *= nums[j]
13
14 result.append(product)
15
16 return result
21 lines
1class Solution:
2 def productExceptSelf(self, nums: List[int]) -> List[int]:
3 n = len(nums)
4 prefix = [1] * n
5 suffix = [1] * n
6
7 # Calculate prefix products
8 for i in range(1, n): # Start from the second element since prefix[0] is already 1
9 prefix[i] = prefix[i - 1] * nums[i - 1]
10
11 # Calculate suffix products
12 for i in range(n - 2, -1, -1): # Start from the second-to-last element and go backwards
13 suffix[i] = suffix[i + 1] * nums[i + 1]
14
15 # Calculate the final result by multiplying prefix and suffix products
16 result = []
17
18 for i in range(n):
19 result.append(prefix[i] * suffix[i])
20
21 return result
20 lines
1class Solution:
2 def productExceptSelf(self, nums: List[int]) -> List[int]:
3 n = len(nums)
4 result = [1] * n
5
6 prefix = 1 # Initialize prefix product
7
8 # Calculate the prefix product for each element
9 for i in range(n):
10 result[i] *= prefix
11 prefix *= nums[i]
12
13 suffix = 1 # Initialize suffix product
14
15 # Calculate the suffix product for each element and multiply it with the prefix product
16 for i in range(n - 1, -1, -1):
17 result[i] *= suffix
18 suffix *= nums[i]
19
20 return result
17 lines
1class Solution:
2 def productExceptSelf(self, nums: List[int]) -> List[int]:
3 n = len(nums)
4 result = [1] * n
5 prefix = 1
6 suffix = 1
7
8 for i in range(n):
9 # Update the result for the current index with the prefix product
10 result[i] *= prefix
11 prefix *= nums[i]
12
13 # Update the result for the current index from the end with the suffix product
14 result[n - 1 - i] *= suffix
15 suffix *= nums[n - 1 - i]
16
17 return result