#238
Product of Array Except Self
MediumArrayPrefix SumPrefix SumSuffix Array
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses two passes to compute the prefix and suffix products, allowing us to calculate the result in linear time without using division. This approach is efficient and avoids redundant calculations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a result array of the same length as nums with all elements set to 1.
- 2Step 2: Compute the prefix products: for each index i, set result[i] to the product of all previous elements (from the start to i-1).
- 3Step 3: Compute the suffix products: iterate from the end of the array, multiplying the current result[i] by the product of all elements after i (from i+1 to end).
- 4Step 4: Return the result array.
solution.py12 lines
1def productExceptSelf(nums):
2 n = len(nums)
3 result = [1] * n
4 prefix = 1
5 for i in range(n):
6 result[i] = prefix
7 prefix *= nums[i]
8 suffix = 1
9 for i in range(n-1, -1, -1):
10 result[i] *= suffix
11 suffix *= nums[i]
12 return resultℹ
Complexity note: The time complexity is O(n) because we make two passes through the array (one for prefix and one for suffix). The space complexity is O(n) due to the result array.
- 1Using prefix and suffix products allows us to avoid division.
- 2Two passes through the array are sufficient to compute the result.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.