Product of Array Except Self
MedPrompt
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
3 approaches with complexity analysis and trade-offs.
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
Walkthrough
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
Time
O(n²) where n is the length of the input array as we use nested loops
Space
O(1) extra space (not counting the output array)
Trade-offs
Pros
Simple to understand and implement
No extra space required except output array
Cons
Time complexity is quadratic
Not efficient for large arrays
Does not meet the required O(n) time complexity
Solutions
Solution
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 walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.