Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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.Follow up: Can you solve the problem in O(1)
extra space complexity? (The output array does not count as extra space for space complexity analysis.)
public class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int prod = 1, zeroCnt = count(begin(nums), end(nums), 0);
if(zeroCnt > 1) return vector<int>(size(nums)); // Case-1
for(auto c : nums)
if(c) prod *= c; // calculate product of all elements except 0
for(auto& c : nums)
if(zeroCnt) c = c ? 0 : prod; // Case-2
else c = prod / c; // Case-3
return nums;
}
};
class Solution:
def productExceptSelf(self, nums):
prod, zero_cnt = reduce(lambda a, b: a*(b if b else 1), nums, 1), nums.count(0)
if zero_cnt > 1: return [0]*len(nums)
for i, c in enumerate(nums):
if zero_cnt: nums[i] = 0 if c else prod
else: nums[i] = prod // c
return nums
In our experience, we suggest you solve this Product of Array Except Self LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Product of Array Except Self LeetCode Solution
I hope this Product of Array Except Self LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>