Problem overview
The method ProductExceptSelf receives an int[] called nums and returns an array of the same length. Entry i of the result is the product of every element of nums except nums[i]. Division is not allowed, and the method should run in O(n) time with O(1) extra space, not counting the returned array.
For nums = {1, 2, 3, 4} the result is {24, 12, 8, 6}: the first entry is 2 * 3 * 4, the second is 1 * 3 * 4, and so on. For {-1, 1, 0, -3, 3} it is {0, 0, 9, 0, 0}. Every product that includes the 0 is 0, and only the entry at the 0's own position leaves it out.
Approach: left product times right product
The obvious plan is to multiply everything and divide by nums[i]. Division is ruled out, and it would fail anyway as soon as the array contains a 0. The brute-force alternative multiplies the other n - 1 elements for each position, which takes O(n²).
The better idea splits each answer in two. The product of all elements except nums[i] is the product of everything to the left of i times the product of everything to the right of i. Both of these are running products, and a running product can be extended by one multiplication per step:
- The left product at
iis the left product ati - 1timesnums[i - 1]. - The right product at
iis the right product ati + 1timesnums[i + 1].
The left products are stored in the answer array itself during a left-to-right pass. The right products are used exactly once each, so a single variable that walks from right to left is enough. That is how the extra space stays at O(1).
Why does this avoid the zero problem? Nothing is ever divided. If the array has a zero, the products that pass over it simply become 0, and the entry at the zero's own position is built only from the elements on its two sides, so it is the one entry that can stay non-zero. The method needs no special case for zeros.
The same idea is often called prefix and suffix products: a prefix product covers the elements before an index, and a suffix product covers the elements after it. Once you see an answer as "everything on the left times everything on the right", the problem reduces to computing those two running products without storing both of them.
Step by step
- Store the length in
n, because both loops run over every index. - Create
answerwithnelements and setanswer[0]to 1. A newint[]is filled with zeros, so this assignment matters. Nothing lies to the left of the first element, and the product of no numbers is 1. - Fill the rest from left to right, starting the loop at 1. Each entry is the previous entry times the previous element of
nums. After this pass,answer[i]holds the product of everything left ofi. - Start
suffixat 1. It will hold the product of everything to the right of the current index. The last element has nothing to its right. - Walk from right to left. At each index, multiply
answer[i]bysuffix. Now it is left product times right product. - Then multiply
suffixbynums[i]. The order matters: ifsuffixabsorbednums[i]first,answer[i]would include the very element it must leave out. - Return
answer.
The solution in C#
class Solution {
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;
}
}
For nums = {1, 2, 3, 4}, the first pass leaves answer as {1, 1, 2, 6}. The second pass then runs like this:
| i | answer[i] after *= suffix | suffix after *= nums[i] |
|---|---|---|
| 3 | 6 | 4 |
| 2 | 8 | 12 |
| 1 | 12 | 24 |
| 0 | 24 | 24 |
The final array is {24, 12, 8, 6}.
C# details worth knowing:
- Arrays start zeroed.
new int[n]contains zeros, which is why the code setsanswer[0] = 1explicitly. A zero there would turn every entry into 0. *=is shorthand.answer[i] *= suffixmeansanswer[i] = answer[i] * suffix, and it evaluates the index once.- Overflow wraps silently.
intarithmetic is unchecked by default. Withint x = int.MaxValue; int y = 2;, the expressionx * ygives-2and no exception. The lesson guarantees every prefix and suffix product fits in 32 bits, so this does not happen here. nums.Lengthis a property, not a method, for arrays. The method needs at least two elements, sinceanswer[0]would throwIndexOutOfRangeExceptionon an empty array.
Complexity
Time: O(n). There are two loops, each visiting every index once with a constant amount of work.
Space: O(1) extra. Apart from the returned array, the method keeps n, suffix and the loop counters. The prefix products live in the output array, which the problem does not count.
Edge cases and common mistakes
- One zero.
{-1, 1, 0, -3, 3}gives{0, 0, 9, 0, 0}. Only the entry at the zero's position is non-zero. No special case is needed, because the products carry the zero along naturally. - Two zeros.
{0, 0, 3}gives{0, 0, 0}: every product includes at least one zero. - Two elements.
{2, 3}gives{3, 2}: each answer is the other element. - Negative numbers.
{5, -2, 1}gives{-2, 5, -10}. The sign comes out right with no extra handling. - Updating
suffixtoo early. Swapping the two lines in the second loop makes each answer include its own element. - Starting
answer[0]at 0 or forgetting it. The default 0 makes the whole array zero. - Starting the first loop at 0. It would read
answer[-1]and throw.
Testing
{1, 2, 3, 4}gives{24, 12, 8, 6}.{-1, 1, 0, -3, 3}gives{0, 0, 9, 0, 0}.{2, 3}gives{3, 2}.{0, 0, 3}gives{0, 0, 0}.{5, -2, 1}gives{-2, 5, -10}.
