Product of Array Except Self Without Division and Overflow Management
The problem requires constructing an array result of length $n$ such that result[i] is equal to the product of all elements of nums except nums[i], without using division and in $O(n)$ time.
When division is disallowed, we construct the product by decomposing each index into two independent segments: $$\text{result}[i] = (\text{product of all elements to the left of } i) \times (\text{product of all elements to the right of } i)$$
Managing Integer Overflow Risk
When performing cumulative product operations, intermediate or final values can easily exceed standard 32-bit signed integers ($[-2^{31}, 2^{31} - 1]$):
- 64-bit Widening (
long long/int64_t): Even if final answers fit within standard 32-bit limits, prefix/suffix multipliers should be stored using 64-bit integer registers during accumulation to eliminate intermediate register overflow. - Modular Arithmetic Option: In competitive programming settings, problems often specify a prime modulus (e.g., $10^9 + 7$). Prefix and suffix accumulations should execute modulo $M$ at every multiplication step: $$\text{prefix} = (\text{prefix} \times \text{nums}[i]) \pmod M$$
- Logarithmic Decomposition (Floating Point alternative): If only the magnitude or relative order is needed without modular reduction, summing logarithms $\sum \log(\vert{}x\vert{})$ avoids integer overflow entirely, though floating-point precision caveats apply.
- Zero-Handling Preservation: If an array contains multiple zeroes, the product for every position is
0. If it contains exactly one zero at index $z$, all positions are0except index $z$. The prefix-suffix decomposition naturally handles zero values without division-by-zero errors.
Optimal Algorithm: Two-Pass Prefix/Suffix Accumulation
To achieve $O(1)$ auxiliary space (excluding the output array itself), we can populate the output array directly with prefix products, and then use a single scalar variable to accumulate suffix products in reverse.
Step-by-Step Procedure:
- Allocate Output Buffer: Initialize
resultof size $n$. - Left-to-Right Pass (Prefix Accumulation):
- Set
result[0] = 1(no elements to the left). - For $i = 1$ to $n - 1$: $$\text{result}[i] = \text{result}[i - 1] \times \text{nums}[i - 1]$$
- At this point,
result[i]contains the product of all elements strictly to the left of index $i$.
- Set
- Right-to-Left Pass (Suffix Accumulation):
- Maintain a running scalar accumulator
suffix = 1. - For $i = n - 1$ down to $0$: $$\text{result}[i] = \text{result}[i] \times \text{suffix}$$ $$\text{suffix} = \text{suffix} \times \text{nums}[i]$$
- This multiplies the accumulated prefix product directly with the suffix product in-place.
- Maintain a running scalar accumulator
Implementation (C++ with 64-bit Safety & Python)
C++ Implementation (Safe 64-bit / Optional Modulo Support)
#include <vector>
#include <cstdint>
// Standard variant using 64-bit integers to prevent accumulator overflow
std::vector<int64_t> productExceptSelf(const std::vector<int>& nums) {
int n = nums.size();
std::vector<int64_t> result(n, 1);
// Pass 1: Construct prefix products directly in result array
int64_t prefix = 1;
for (int i = 0; i < n; ++i) {
result[i] = prefix;
prefix *= nums[i]; // Casts to 64-bit to prevent overflow
}
// Pass 2: Accumulate suffix products and combine with prefix
int64_t suffix = 1;
for (int i = n - 1; i >= 0; --i) {
result[i] *= suffix;
suffix *= nums[i];
}
return result;
}
// Modular arithmetic variant: Used when results can exceed 64-bit integers
std::vector<int> productExceptSelfMod(const std::vector<int>& nums, int mod) {
int n = nums.size();
std::vector<int> result(n, 1);
long long prefix = 1;
for (int i = 0; i < n; ++i) {
result[i] = prefix;
prefix = (prefix * (nums[i] % mod + mod)) % mod;
}
long long suffix = 1;
for (int i = n - 1; i >= 0; --i) {
result[i] = (result[i] * suffix) % mod;
suffix = (suffix * (nums[i] % mod + mod)) % mod;
}
return result;
}
Python Implementation (Arbitrary-Precision Arithmetic)
def product_except_self(nums: list[int]) -> list[int]:
n = len(nums)
# Python automatically promotes integers to arbitrary precision,
# completely eliminating integer overflow hazards.
result = [1] * n
# Pass 1: Prefix products
prefix = 1
for i in range(n):
result[i] = prefix
prefix *= nums[i]
# Pass 2: Suffix products
suffix = 1
for i in range(n - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return result
Complexity Analysis
| Metric | Complexity | Details |
|---|---|---|
| Time Complexity | $O(n)$ | Requires two sequential linear passes through the array of length $n$. No nested iterations. |
| Auxiliary Space | $O(1)$ | If the returned array is excluded from memory overhead, only scalar accumulators (prefix, suffix) are allocated. |
| Division Count | $0$ | Does not use / or % (except in the explicit modular reduction case), preventing undefined behavior when encountering zeroes. |
