Algo-Sim › Arrays & Hashing
Product of Array Except Self
Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input
answer[i] is the product of every element except nums[i], computed without division from prefix and suffix products.
Problem
Given an integer array nums, build an array answer where answer[i] is the product of every element of nums except nums[i]. Do it in O(n) time without using division.
Constraints
- 2 ≤ nums.length ≤ 10⁵
- -30 ≤ nums[i] ≤ 30
- Every prefix and suffix product fits in a 32-bit integer
- No division; O(1) extra space besides the output is the follow-up
Edge cases to test
- One zero: only that index is non-zero
- Two zeros: every answer is 0
- Negative values
Follow-up questions
- Can you do it in O(1) extra space?
- Write the prefix products into the output array, then sweep from the right with one running suffix product: O(n) time, O(1) extra.
- Why not divide the total product by nums[i]?
- Division fails on zeros (and the task forbids it). Counting zeros and dividing works but overflows sooner than prefix and suffix products.
Solution
Java
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] answer = new int[n];
answer[0] = 1;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}
int suffix = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
}Python
def product_except_self(nums):
n = len(nums)
answer = [1] * n
for i in range(1, n):
answer[i] = answer[i - 1] * nums[i - 1]
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answerC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int> &nums) {
int n = int(nums.size());
vector<int> answer = vector<int>(n);
answer[0] = 1;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}
int suffix = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)