Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in Scala: O(n), No Division

Practice O(n) Read the full explanation

You get an array of integers nums.

Return an array answer of the same length.

answer[i] is the product of all the numbers in nums, except the one at index i.

Don't use division.

 

Example 1:

Input: nums = [2,5,1,3]
Output: [15,6,30,10]
Explanation:
answer[0] = 5 * 1 * 3 = 15,
answer[1] = 2 * 1 * 3 = 6,
answer[2] = 2 * 5 * 3 = 30,
answer[3] = 2 * 5 * 1 = 10.

Example 2:

Input: nums = [4,0,-2,5]
Output: [0,-40,0,0]
Explanation: Every product that includes the 0 is 0.
Only answer[1] leaves the 0 out:
answer[1] = 4 * (-2) * 5 = -40.

Example 3:

Input: nums = [0,6,0]
Output: [0,0,0]
Explanation: There are two zeros.
Every product still includes at least one of them.

 

Constraints:

  • nums has 2 to 100,000 numbers.
  • Each number is from -30 to 30.
  • Every answer[i] fits in a 32-bit signed integer.
  • So does the product of all the numbers before any index, or after it.

Note:

Your algorithm should run in O(n) time and use O(1) extra space: the returned array doesn't count.

STEP 1 OF 9
    Ctrl + Enter to check

    SCALA · PARTIAL SUMS #1

    Product Of Array Except Self in Scala, explained

    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 index i. Each entry comes from the previous one: answer(i) is answer(i - 1) times nums(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 into answer(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

    1. Store the length. val n = nums.length is used by both loops.
    2. Create answer and set answer(0) to 1. Array.fill(n)(0) makes an Array[Int] of n zeros. 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.
    3. Loop from index 1 to n - 1. 1 until n excludes n and starts after the entry that is already set.
    4. Extend the prefix product. answer(i) is answer(i - 1) * nums(i - 1): the product to the left of i - 1, times the element at i - 1 itself.
    5. Create suffix as a var set to 1. It changes on every step of the second loop, so it can't be a val. It starts at 1 because the last element has nothing to its right.
    6. Walk from right to left. n - 1 to 0 by -1 includes both ends and counts down.
    7. Multiply suffix into answer(i) with *=. Now the entry is the left product times the right product.
    8. Then multiply suffix by nums(i). The order matters: answer(i) must not include nums(i) itself, so suffix grows only after it has been used.
    9. Return answer as 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) and answer(i) = value, not square brackets. Both are method calls on Array that the compiler turns into plain array access.
    • val arrays can still change. val answer means the name can't point to another array. Its elements are mutable, so answer(i) = ... is allowed.
    • *= on an element. answer(i) *= suffix is shorthand for answer(i) = answer(i) * suffix.
    • until versus to. 1 until n stops before n; n - 1 to 0 by -1 includes 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 bare answer on the final line is the method's result.
    • Int is 32 bits. Overflow wraps silently, with no exception. The lesson's constraints promise that every product fits, but with Array(2000000000, 2, 3) the result is Array(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 is Array(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) gives Array(3, 2): each entry is the other element.
    • Starting suffix or answer(0) at 0. Everything would multiply to 0. Both start at 1, the identity for multiplication.
    • Updating suffix first. Swapping the two lines in the second loop multiplies nums(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) = 1 throws an ArrayIndexOutOfBoundsException, because the array has no index 0. A one-element array returns Array(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].
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free