product-of-array-except-self

This commit is contained in:
Sangeeth Sudheer 2022-04-21 17:06:14 +05:30
parent d86e3334b1
commit 80245886a1
3 changed files with 58 additions and 0 deletions

View File

@ -0,0 +1,8 @@
## What if we were allowed to use division?
Well, one might think that you can then find product(nums) and divide by nums[i] in the loop. But the problem with this approach is when there are 0s in the array. That causes the entire product to become zero.
So, we probably need to keep track of zero count and the first zero index.
1. If there are >1 zeroes, then the result would be all zeroes so.
2. If there's only 1 zero, then we need to keep product excluding the zero to be kept. Then fill the result with all zeroes except for the 0 element's index which would equal the product.

View File

@ -0,0 +1,25 @@
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`
* The product of any prefix or suffix of `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.)

View File

@ -0,0 +1,25 @@
from functools import reduce
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# We can divide this problem by finding the prefix and
# postfix products of a given element and then multiplying
# them together
result = [0] * len(nums)
# Find prefix products, i.e, for ith element, store
# product of 0 to a[i - 1]
prefix = 1
for i, num in enumerate(nums):
result[i] = prefix
prefix *= num
# Find suffix products by iterating from the last, and
# combine them with prefix in the same step to reduce cost
suffix = 1
for i in range(len(nums) - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return result