Problem overview
The method productExceptSelf takes an Array[Int] named nums and returns an array of the same length. Entry i of the result is the product of every element of nums except the one at index i. Division is not allowed.
For nums = Array(1, 2, 3, 4) the result is Array(24, 12, 8, 6): the first entry is 2 * 3 * 4, the second is 1 * 3 * 4, and so on. A zero in the input is fine. For Array(-1, 1, 0, -3, 3) the result is Array(0, 0, 9, 0, 0), because every product that includes the zero is zero, and only index 2 leaves it out.
Approach: products from the left, then from the right
The obvious solution multiplies everything and divides by nums(i) for each entry. It fails twice: division is banned, and a zero in the input would mean dividing by zero. Another obvious solution uses two nested loops that multiply all the other elements for every index, which takes O(n²) time.
The faster idea splits each answer in two parts. The product of everything except nums(i) is the product of everything to its left times the product of everything to its right. Both parts can be built with one running product each:
- A left-to-right pass stores, in
answer(i), the product of the elements before indexi. Each entry comes from the previous one:answer(i)isanswer(i - 1)timesnums(i - 1). - A right-to-left pass keeps a single variable,
suffix, holding the product of the elements after the current index, and multiplies it intoanswer(i).
The first pass fills the result array, and the second only updates it, so no other array is needed. The extra memory is one variable, O(1), since the returned array doesn't count. The time is two passes, O(n).
Step by step
- Store the length.
val n = nums.lengthis used by both loops. - Create
answerand setanswer(0)to 1.Array.fill(n)(0)makes anArray[Int]ofnzeros. Nothing lies to the left of the first element, and a product of no numbers is 1, the same way a sum of no numbers is 0. - Loop from index 1 to
n - 1.1 until nexcludesnand starts after the entry that is already set. - Extend the prefix product.
answer(i)isanswer(i - 1) * nums(i - 1): the product to the left ofi - 1, times the element ati - 1itself. - Create
suffixas avarset to 1. It changes on every step of the second loop, so it can't be aval. It starts at 1 because the last element has nothing to its right. - Walk from right to left.
n - 1 to 0 by -1includes both ends and counts down. - Multiply
suffixintoanswer(i)with*=. Now the entry is the left product times the right product. - Then multiply
suffixbynums(i). The order matters:answer(i)must not includenums(i)itself, sosuffixgrows only after it has been used. - Return
answeras the last expression of the method.
Tracing Array(1, 2, 3, 4) shows the two passes. After the first pass, answer is [1,1,2,6]. The second pass then runs like this:
i=3 answer=[1,1,2,6] suffix=4
i=2 answer=[1,1,8,6] suffix=12
i=1 answer=[1,12,8,6] suffix=24
i=0 answer=[24,12,8,6] suffix=24
Each line shows the array and suffix after the loop body ran for that i. The last suffix value isn't used by anything; the loop just ends.
The solution in Scala
class Solution {
def productExceptSelf(nums: Array[Int]): Array[Int] = {
val n = nums.length
val answer = Array.fill(n)(0)
answer(0) = 1
for (i <- 1 until n) {
answer(i) = answer(i - 1) * nums(i - 1)
}
var suffix = 1
for (i <- n - 1 to 0 by -1) {
answer(i) *= suffix
suffix *= nums(i)
}
answer
}
}
Scala details worth knowing:
- Arrays use parentheses. Scala reads and writes elements with
answer(i)andanswer(i) = value, not square brackets. Both are method calls onArraythat the compiler turns into plain array access. valarrays can still change.val answermeans the name can't point to another array. Its elements are mutable, soanswer(i) = ...is allowed.*=on an element.answer(i) *= suffixis shorthand foranswer(i) = answer(i) * suffix.untilversusto.1 until nstops beforen;n - 1 to 0 by -1includes 0. Mixing them up skips an index or goes out of bounds.- No
return. The last expression of a block is its value, so the bareansweron the final line is the method's result. Intis 32 bits. Overflow wraps silently, with no exception. The lesson's constraints promise that every product fits, but withArray(2000000000, 2, 3)the result isArray(6, 1705032704, -294967296).
Complexity
Time: O(n). The method makes one pass from the left and one from the right, with a constant amount of work per element.
Space: O(1) extra. Besides the returned array, only n and suffix are stored. Keeping a second array of suffix products would work too, but would cost O(n) extra space.
Edge cases and common mistakes
- One zero. For
Array(5, 0, 4)the result isArray(0, 20, 0). Only the zero's own index gets a non-zero product, which is why dividing the total by each element could never work. - Two or more zeros. For
Array(0, 0, 2)every entry is 0, since each product contains at least one zero. - Two elements.
Array(2, 3)givesArray(3, 2): each entry is the other element. - Starting
suffixoranswer(0)at 0. Everything would multiply to 0. Both start at 1, the identity for multiplication. - Updating
suffixfirst. Swapping the two lines in the second loop multipliesnums(i)into its own answer, so each entry would include the element that must be left out. - Fewer than two elements. The lesson guarantees at least two. With an empty array,
answer(0) = 1throws anArrayIndexOutOfBoundsException, because the array has no index 0. A one-element array returnsArray(1).
Testing
Array(1, 2, 3, 4)gives[24,12,8,6].Array(-1, 1, 0, -3, 3)gives[0,0,9,0,0].Array(2, 3)gives[3,2].Array(0, 0, 2)gives[0,0,0].Array(5, 0, 4)gives[0,20,0].
