Problem overview
The function productExceptSelf receives an IntArray named nums and returns an IntArray 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 work must take O(n) time with O(1) extra space, where the returned array doesn't count as extra.
For [1, 2, 3, 4] the answer 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 zero is zero, and only the entry at the zero's own index leaves it out. With two elements, each entry is simply the other element: [2, 3] gives [3, 2].
Approach
The obvious plan is to multiply everything and divide by nums[i] for each entry. The statement forbids division, and it would fail anyway when the array holds a zero. The next idea is a nested loop that multiplies all the other elements for each index. That is correct but takes O(n^2) time, too slow for 100,000 elements.
The faster idea is to split each answer in two. The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Both sides can be built with running products:
- A left-to-right pass stores, in
answer[i], the product of all elements before indexi(prefix products). - A right-to-left pass keeps one variable,
suffix, holding the product of all elements after indexi, and multiplies it intoanswer[i].
The result array itself stores the left products, and one variable holds the right side, so no extra array is needed. That is where the O(1) extra space comes from.
Step by step
- Store the length.
val n = nums.size, because both loops run over every index. - Create the result.
IntArray(n)starts filled with zeros. Setanswer[0]to 1: nothing lies to the left of the first element, and a product of no numbers is 1. Thevalonly means the name can't point at another array; the elements can still change. - Prefix pass. Loop
iover1 until n, since index 0 is already set. Each entry is the previous entry times the previous element:answer[i] = answer[i - 1] * nums[i - 1]. For[1, 2, 3, 4]this leaves[1, 1, 2, 6]inanswer. - Start the suffix.
var suffix = 1. It is avarbecause it changes on every step, and it starts at 1 because the last element has nothing to its right. - Suffix pass. Loop
iovern - 1 downTo 0;downToincludes 0. - Combine.
answer[i] *= suffixturns the left product into left times right. - Extend the suffix.
suffix *= nums[i], so that it also coversnums[i]when the loop moves one step left. This line must come after the previous one: otherwiseanswer[i]would includenums[i]itself. - Return
answer.
Running the second pass on [1, 2, 3, 4] and printing answer[i] and suffix after each iteration gives:
i=3 answer[i]=6 suffix=4
i=2 answer[i]=8 suffix=12
i=1 answer[i]=12 suffix=24
i=0 answer[i]=24 suffix=24
The solution in Kotlin
class Solution {
fun productExceptSelf(nums: IntArray): IntArray {
val n = nums.size
val answer = IntArray(n)
answer[0] = 1
for (i in 1 until n) {
answer[i] = answer[i - 1] * nums[i - 1]
}
var suffix = 1
for (i in n - 1 downTo 0) {
answer[i] *= suffix
suffix *= nums[i]
}
return answer
}
}
Some Kotlin details worth knowing:
1 until nexcludesn, whilen - 1 downTo 0counts down and includes both ends. Inn - 1 downTo 0the subtraction happens first, so the loop starts at the last valid index.IntArrayholds primitiveintvalues and is zero-filled on creation. Printing one directly shows a type tag and a hash such as[I@followed by digits, not the numbers; usecontentToString()to see the numbers.Intis 32 bits and overflow wraps silently. The constraints promise that every prefix, suffix and answer fits, so noLongis needed here.answer[i] *= suffixis shorthand foranswer[i] = answer[i] * suffixand works on array elements.
Why the two passes don't interfere
When the second loop reaches index i, answer[i] still holds only the left product, because the loop works from the right and has not touched index i before. At that moment suffix holds the product of nums[i + 1] through nums[n - 1]. Multiplying them gives exactly the product of everything except nums[i]. Only after that does suffix grow to include nums[i] for the next, smaller index.
Complexity
Time is O(n): two passes, each doing constant work per element. Extra space is O(1): the only additions are n and suffix. The result array is required output, so it isn't counted.
Edge cases and common mistakes
- Zeros. Because no division is used, zeros need no special handling.
[5, 0, 4]gives[0, 20, 0]and[0, 0, 2]gives[0, 0, 0]. - Two elements.
[2, 3]gives[3, 2]. The constraints guarantee at least two elements, soanswer[0] = 1is always a valid index. - Swapping the last two lines. Updating
suffixbefore multiplying intoanswer[i]makes each entry include its own element. - Starting a product at 0. The starting value for a product is 1, not 0.
- Looping the prefix pass from 0. That would read
answer[-1]and throw anArrayIndexOutOfBoundsException.
Testing
Inputs worth trying, with the results the solution returns:
[1, 2, 3, 4] -> [24, 12, 8, 6]
[-1, 1, 0, -3, 3] -> [0, 0, 9, 0, 0]
[2, 3] -> [3, 2]
[0, 0, 2] -> [0, 0, 0]
[5, 0, 4] -> [0, 20, 0]
