1. Explicit Left & Right Product Arrays
Build separate leftProducts and rightProducts arrays, then multiply leftProducts[i] * rightProducts[i] for every index.
Three linear loops over n elements.
Allocates two auxiliary arrays of size n alongside the output array.
How It Works
Splitting Left and Right Dependencies
Rather than mutating the result array twice, store both sides explicitly:
left[i]= product of all elements strictly beforei(left[0] = 1).right[i]= product of all elements strictly afteri(right[n - 1] = 1).answer[i] = left[i] * right[i].
This uses O(n) extra space, making the invariants easy to inspect before optimizing space to O(1).
Step-by-Step Dry Run
left[0] = 1, left[1] = 1, left[2] = 2, left[3] = 6.
left = [1, 1, 2, 6]- +Zero in-place mutation confusion
- +Crystal-clear prefix and suffix separation
- -Allocates 2 extra O(n) arrays instead of reusing the return buffer
Reference Implementation
Complete implementation for Explicit Left & Right Product Arrays in Python, JavaScript, Java, C++, and C.
def product_except_self_arrays(nums: list[int]) -> list[int]:n = len(nums)left = [1] * nright = [1] * nfor i in range(1, n):left[i] = left[i - 1] * nums[i - 1]for i in range(n - 2, -1, -1):right[i] = right[i + 1] * nums[i + 1]return [left[i] * right[i] for i in range(n)]
function productExceptSelfArrays(nums) {
const n = nums.length;
const left = new Array(n).fill(1);
const right = new Array(n).fill(1);
for (let i = 1; i < n; i++) left[i] = left[i - 1] * nums[i - 1];
for (let i = n - 2; i >= 0; i--) right[i] = right[i + 1] * nums[i + 1];
return nums.map((_, i) => left[i] * right[i]);
}public class Solution {
public static int[] productExceptSelfArrays(int[] nums) {
int n = nums.length;
int[] left = new int[n];
int[] right = new int[n];
int[] ans = new int[n];
left[0] = 1;
right[n - 1] = 1;
for (int i = 1; i < n; i++) left[i] = left[i - 1] * nums[i - 1];
for (int i = n - 2; i >= 0; i--) right[i] = right[i + 1] * nums[i + 1];
for (int i = 0; i < n; i++) ans[i] = left[i] * right[i];
return ans;
}
}#include <vector>
std::vector<int> productExceptSelfArrays(const std::vector<int>& nums) {
int n = static_cast<int>(nums.size());
std::vector<int> left(n, 1), right(n, 1), ans(n);
for (int i = 1; i < n; i++) left[i] = left[i - 1] * nums[i - 1];
for (int i = n - 2; i >= 0; i--) right[i] = right[i + 1] * nums[i + 1];
for (int i = 0; i < n; i++) ans[i] = left[i] * right[i];
return ans;
}#include <stdlib.h>
int* productExceptSelfArrays(const int* nums, int n, int* returnSize) {
*returnSize = n;
int* left = (int*)malloc(n * sizeof(int));
int* right = (int*)malloc(n * sizeof(int));
int* ans = (int*)malloc(n * sizeof(int));
left[0] = 1;
right[n - 1] = 1;
for (int i = 1; i < n; i++) left[i] = left[i - 1] * nums[i - 1];
for (int i = n - 2; i >= 0; i--) right[i] = right[i + 1] * nums[i + 1];
for (int i = 0; i < n; i++) ans[i] = left[i] * right[i];
free(left);
free(right);
return ans;
}