Leetcode 238. Product of Array Except Self
Given an array nums
of n
integers where n > 1
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
You should solve it without using division and in O(n).
To achieve the desired output without using division and ensuring that the time complexity remains O(n), we can follow these steps:
left
and right
, of length n
.
left[i]
will contain the product of all elements to the left of index i
.right[i]
will contain the product of all elements to the right of index i
.left
array:
left[0]
to 1 because there are no elements to the left of the first element.left
array.right
array:
right[n-1]
to 1 because there are no elements to the right of the last element.right
array.i
, the result at i
will be left[i] * right[i]
.#include <vector>
using namespace std;
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> left(n, 1);
vector<int> right(n, 1);
vector<int> result(n);
// Fill in the left array
for (int i = 1; i < n; ++i) {
left[i] = left[i - 1] * nums[i - 1];
}
// Fill in the right array
for (int i = n - 2; i >= 0; --i) {
right[i] = right[i + 1] * nums[i + 1];
}
// Fill in the result array
for (int i = 0; i < n; ++i) {
result[i] = left[i] * right[i];
}
return result;
}
left
and right
arrays, and once more to fill the result
array.n
, left
and right
, making the space complexity linear.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?