Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in Swift: O(n) Without 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

    SWIFT · PARTIAL SUMS #1

    Product Of Array Except Self in Swift, explained

    Problem overview

    The method productExceptSelf receives an array of integers, 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]. The statement forbids division, and it asks for O(n) time and O(1) extra space, where the returned array doesn't count.

    For nums = [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] the answer 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 products, then right products

    The obvious plan multiplies everything and divides by nums[i]. It fails twice: division is banned, and a 0 in the array makes the division meaningless. The next idea, a nested loop that multiplies the other n - 1 elements for each position, works but costs O(n²).

    The faster idea splits 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:

    • The product to the left of i is the product to the left of i - 1 times nums[i - 1]. These are prefix products.
    • The product to the right of i is built the same way, walking from the end.

    Storing both sides in two extra arrays would work. The lesson saves memory instead: the first pass stores the left products directly in answer, and the second pass walks right to left with one running variable, suffix, and multiplies it into answer as it goes. Each right-side product is needed exactly once, so one variable is enough.

    On [1, 2, 3, 4], the first pass leaves answer as [1, 1, 2, 6]. The second pass then goes 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 state after the loop body for that i. The last entry changes first because nothing lies to its right, so its multiplier is the starting value of suffix, 1.

    Step by step

    1. Store the length. nums.count goes into a let named n, because both loops need it.
    2. Create answer. It is a var array of n zeros, and answer[0] is set to 1. Nothing lies to the left of the first element, and a product of no numbers is 1, just as an empty sum is 0.
    3. Loop from 1 up to n - 1. Index 0 is already filled.
    4. Extend the prefix product. answer[i] becomes answer[i - 1] * nums[i - 1]: the product up to the previous position, times the previous element.
    5. Start suffix at 1. It holds the product of everything to the right of the current index, and it must be a var because it changes on every step.
    6. Walk from right to left with stride(from: n - 1, through: 0, by: -1), which counts down and includes 0.
    7. Multiply answer[i] by suffix. The entry held the left product, so it now holds left times right.
    8. Then fold nums[i] into suffix. The order matters: answer[i] must not include nums[i] itself, so this line comes second. The next position to the left gets a suffix that covers nums[i].
    9. Return answer.

    The solution in Swift

    class Solution {
        func productExceptSelf(_ nums: [Int]) -> [Int] {
            let n = nums.count
            var answer = [Int](repeating: 0, count: n)
            answer[0] = 1
            for i in 1..<n {
                answer[i] = answer[i - 1] * nums[i - 1]
            }
            var suffix = 1
            for i in stride(from: n - 1, through: 0, by: -1) {
                answer[i] *= suffix
                suffix *= nums[i]
            }
            return answer
        }
    }
    

    Swift details worth knowing:

    • [Int](repeating: 0, count: n) builds an array of n copies of 0. Since answer is a var, its elements can be assigned and updated with *=.
    • 1..<n is a half-open range. It covers 1 up to n - 1 and is empty when n is 1. A range whose start is above its end, such as 1..<0, stops the program with an error, which is one reason Swift code counts down with stride instead.
    • stride(from:through:by:) includes the end value (through), while stride(from:to:by:) excludes it. A negative step counts down.
    • Arrays are values. answer is a local array that the method returns, so the caller receives its own copy and nums is never changed.
    • Overflow traps. Int is 64 bits, and in Swift an overflowing * stops the program rather than wrapping silently, even in an optimized build. The constraints promise that every product fits in 32 bits, so the lesson's tests never come near it. With larger values, such as twenty 30s, the same code crashes.

    Complexity

    Time: O(n). Each of the two loops visits every index once and does a constant amount of work per index.

    Space: O(1) extra. Apart from the returned array, the method keeps only n, suffix and the loop variable.

    Edge cases and common mistakes

    • Zeros. [0, 0, 2] gives [0, 0, 0]. With one zero, every entry except the zero's own position is 0, and with two or more, every entry is. The method needs no special case because it never divides.
    • Two elements. [2, 3] gives [3, 2]: each answer is the other element.
    • Negative numbers. [5, -5] gives [-5, 5]. Signs simply follow the multiplication.
    • Swapping the two suffix lines. If suffix *= nums[i] runs before answer[i] *= suffix, every entry also includes its own element.
    • Starting answer[0] or suffix at 0. Everything multiplies by 0, so the whole result is zeros. The starting value of a product is 1.
    • Empty input. The constraints promise at least two elements. With an empty array, answer[0] = 1 would be an index out of range, which stops the program.

    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, 2] gives [0, 0, 0].
    • [5, -5] gives [-5, 5].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free