Product of Array Except Self
MEDIUMDescription
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 input is generated such that
answer[i]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.)
Approaches
Checkout 3 different approaches to solve Product of Array Except Self. Click on different approaches to view the approach and algorithm in detail.
Brute Force Approach
For each index i, iterate through the array and calculate the product of all elements except nums[i].
Algorithm
- Initialize result array of same length as input array
- For each index i in the array:
- Initialize product as 1
- Iterate through array again
- Multiply all elements except nums[i] to product
- Store product in result[i]
- Return result array
The brute force approach involves using nested loops. For each element at index i, we iterate through the array again to calculate the product of all elements except the current element.
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
int product = 1;
for (int j = 0; j < n; j++) {
if (i != j) {
product *= nums[j];
}
}
result[i] = product;
}
return result;
}
Complexity Analysis
Pros and Cons
- Simple to understand and implement
- No extra space required except output array
- Time complexity is quadratic
- Not efficient for large arrays
- Does not meet the required O(n) time complexity
Code Solutions
Checking out 5 solutions in different languages for Product of Array Except Self. Click on different languages to view the code.
public class Solution {
public int[] ProductExceptSelf(int[] nums) {
int n = nums.Length;
int[] ans = new int[n];
for (int i = 0, left = 1; i < n; ++i) {
ans[i] = left;
left *= nums[i];
}
for (int i = n - 1, right = 1; i >= 0; --i) {
ans[i] *= right;
right *= nums[i];
}
return ans;
}
}Video Solution
Watch the video walkthrough for Product of Array Except Self
Similar Questions
5 related questions you might find useful
Patterns:
Data Structures:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.