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.
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
nums
is guaranteed to fit in a 32-bit integer.
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] right = new int[n];
int pro = 1 ;
for(int i=n-1;i>=0;i--){
pro = pro * nums[i];
right[i] = pro ;
}
int[] ans = new int[n];
int left = 1 ;
for(int i=0;i
class Solution {
public:
vector productExceptSelf(vector& nums) {
int n=nums.size();
vector leftpr(n,1);
vector rightpr(n,1);
for(int i=1;i=0; i--)
{
rightpr[i]=rightpr[i+1]*nums[i+1];
}
for(int i=0; i
In this program we have to reverse the order of words,but keeping the word’s direction in the same way. Only the words will be interchanged .
In this question , We have to find the product of every element in an array except itself.
In simpler terms , we have to find a new list where each number is the result of multiplying all the numbers in the original list, except the one at the same position.
In this approach we have to maintain the time complexity of O(n) and space complexity’s O(n).
Let’s see the step-by-step approach of the code:
1.For this purpose we are using two additional arrays, ‘leftptr’ and ‘rightptr’ , to store the product of elements to the left and right of each element, respectively.
Multiply left[ i -1] * nums [ i -1 ]
Then we can get the product upto (i-1)th position.
In this way we are able to find out the product of all the backward elements from the current position in an array.
Right[i+1] * num[ i+1]
Vector<int> leftpr( n, 1);
Vector<int> rightpr( n, 1);
Finally, the modified ‘nums’ vector containing the product of all elements except for the element at the current index, is returned.
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India