Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in Kotlin: O(n) Time, O(1) Extra Space

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

    KOTLIN · PARTIAL SUMS #1

    Product Of Array Except Self in Kotlin, explained

    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 index i (prefix products).
    • A right-to-left pass keeps one variable, suffix, holding the product of all elements after index i, and multiplies it into answer[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

    1. Store the length. val n = nums.size, because both loops run over every index.
    2. Create the result. IntArray(n) starts filled with zeros. Set answer[0] to 1: nothing lies to the left of the first element, and a product of no numbers is 1. The val only means the name can't point at another array; the elements can still change.
    3. Prefix pass. Loop i over 1 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] in answer.
    4. Start the suffix. var suffix = 1. It is a var because it changes on every step, and it starts at 1 because the last element has nothing to its right.
    5. Suffix pass. Loop i over n - 1 downTo 0; downTo includes 0.
    6. Combine. answer[i] *= suffix turns the left product into left times right.
    7. Extend the suffix. suffix *= nums[i], so that it also covers nums[i] when the loop moves one step left. This line must come after the previous one: otherwise answer[i] would include nums[i] itself.
    8. 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 n excludes n, while n - 1 downTo 0 counts down and includes both ends. In n - 1 downTo 0 the subtraction happens first, so the loop starts at the last valid index.
    • IntArray holds primitive int values 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; use contentToString() to see the numbers.
    • Int is 32 bits and overflow wraps silently. The constraints promise that every prefix, suffix and answer fits, so no Long is needed here.
    • answer[i] *= suffix is shorthand for answer[i] = answer[i] * suffix and 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, so answer[0] = 1 is always a valid index.
    • Swapping the last two lines. Updating suffix before multiplying into answer[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 an ArrayIndexOutOfBoundsException.

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