Top Interview 150
This problem challenges you to compute a product array without directly using division, making it a test of algorithmic efficiency and logical thinking. Let's break down LeetCode 238: Product of Array Except Self and implement a solution in O(n)
time.
π Problem Description
Given an integer array nums
, return an array answer where:
-
answer[i]
is the product of all elements innums
exceptnums[i]
. - You must solve it without division and in
O(n)
time.
π‘ Examples
Example 1
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Explanation:
- `answer[0] = 2 * 3 * 4 = 24`
- `answer[1] = 1 * 3 * 4 = 12`
- `answer[2] = 1 * 2 * 4 = 8`
- `answer[3] = 1 * 2 * 3 = 6`
Example 2
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Explanation:
- `answer[2] = -1 * 1 * -3 * 3 = 9`
- For all other indices, the product includes `0`.
π JavaScript Solution
The solution involves using two prefix
and suffix
arrays to calculate the product of all elements except the current index without division.
var productExceptSelf = function(nums) {
let n = nums.length;
let answer = new Array(n).fill(1);
let prefix = 1;
for (let i = 0; i < n; i++) {
answer[i] = prefix;
prefix *= nums[i];
}
let suffix = 1;
for (let i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
};
π How It Works
-
Prefix Product Pass:
- Compute the cumulative product of elements to the left of each index and store it in the
answer
array.
- Compute the cumulative product of elements to the left of each index and store it in the
-
Suffix Product Pass:
- Traverse the array from right to left and multiply the cumulative product of elements to the right of each index with the value in
answer
.
- Traverse the array from right to left and multiply the cumulative product of elements to the right of each index with the value in
The result is an array where each element is the product of all other elements except itself.
π Complexity Analysis
- > Time Complexity:
O(n)
, since we traverse the array twice (once for prefix and once for suffix). - > Space Complexity:
O(1)
(ignoring the output array), as we do not use any additional data structures apart from the result array.
π Dry Run
Input: nums = [1,2,3,4]
Output: [24, 12, 8, 6]
β¨ Pro Tips for Interviews
- Clarify requirements: Confirm whether division is allowed (itβs not in this problem).
- Handle edge cases:
- Single-element array (
[a] β [1]
). - Arrays with zeros (
[0,1,2] β [2,0,0]
).
- Single-element array (
- Optimize space: Explain how avoiding auxiliary arrays reduces space complexity.
π Learn More
Check out the full explanation and code walkthrough on my Dev.to post:
π Insert Delete GetRandom O(1) - JavaScript Solution
How would you solve this problem? Letβs discuss below! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!