Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in C#: Prefix and Suffix Products

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

    C# · PARTIAL SUMS #1

    Product Of Array Except Self in C#, explained

    Problem overview

    The method ProductExceptSelf receives an int[] called 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]. Division is not allowed, and the method should run in O(n) time with O(1) extra space, not counting the returned array.

    For nums = {1, 2, 3, 4} the result 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 0 is 0, and only the entry at the 0's own position leaves it out.

    Approach: left product times right product

    The obvious plan is to multiply everything and divide by nums[i]. Division is ruled out, and it would fail anyway as soon as the array contains a 0. The brute-force alternative multiplies the other n - 1 elements for each position, which takes O(n²).

    The better idea splits each answer in two. The product of all elements except nums[i] is the product of everything to the left of i times the product of everything to the right of i. Both of these are running products, and a running product can be extended by one multiplication per step:

    • The left product at i is the left product at i - 1 times nums[i - 1].
    • The right product at i is the right product at i + 1 times nums[i + 1].

    The left products are stored in the answer array itself during a left-to-right pass. The right products are used exactly once each, so a single variable that walks from right to left is enough. That is how the extra space stays at O(1).

    Why does this avoid the zero problem? Nothing is ever divided. If the array has a zero, the products that pass over it simply become 0, and the entry at the zero's own position is built only from the elements on its two sides, so it is the one entry that can stay non-zero. The method needs no special case for zeros.

    The same idea is often called prefix and suffix products: a prefix product covers the elements before an index, and a suffix product covers the elements after it. Once you see an answer as "everything on the left times everything on the right", the problem reduces to computing those two running products without storing both of them.

    Step by step

    1. Store the length in n, because both loops run over every index.
    2. Create answer with n elements and set answer[0] to 1. A new int[] is filled with zeros, so this assignment matters. Nothing lies to the left of the first element, and the product of no numbers is 1.
    3. Fill the rest from left to right, starting the loop at 1. Each entry is the previous entry times the previous element of nums. After this pass, answer[i] holds the product of everything left of i.
    4. Start suffix at 1. It will hold the product of everything to the right of the current index. The last element has nothing to its right.
    5. Walk from right to left. At each index, multiply answer[i] by suffix. Now it is left product times right product.
    6. Then multiply suffix by nums[i]. The order matters: if suffix absorbed nums[i] first, answer[i] would include the very element it must leave out.
    7. Return answer.

    The solution in C#

    class Solution {
        public int[] ProductExceptSelf(int[] nums) {
            int n = nums.Length;
            int[] answer = new int[n];
            answer[0] = 1;
            for (int i = 1; i < n; i++) {
                answer[i] = answer[i - 1] * nums[i - 1];
            }
            int suffix = 1;
            for (int i = n - 1; i >= 0; i--) {
                answer[i] *= suffix;
                suffix *= nums[i];
            }
            return answer;
        }
    }
    

    For nums = {1, 2, 3, 4}, the first pass leaves answer as {1, 1, 2, 6}. The second pass then runs like this:

    ianswer[i] after *= suffixsuffix after *= nums[i]
    364
    2812
    11224
    02424

    The final array is {24, 12, 8, 6}.

    C# details worth knowing:

    • Arrays start zeroed. new int[n] contains zeros, which is why the code sets answer[0] = 1 explicitly. A zero there would turn every entry into 0.
    • *= is shorthand. answer[i] *= suffix means answer[i] = answer[i] * suffix, and it evaluates the index once.
    • Overflow wraps silently. int arithmetic is unchecked by default. With int x = int.MaxValue; int y = 2;, the expression x * y gives -2 and no exception. The lesson guarantees every prefix and suffix product fits in 32 bits, so this does not happen here.
    • nums.Length is a property, not a method, for arrays. The method needs at least two elements, since answer[0] would throw IndexOutOfRangeException on an empty array.

    Complexity

    Time: O(n). There are two loops, each visiting every index once with a constant amount of work.

    Space: O(1) extra. Apart from the returned array, the method keeps n, suffix and the loop counters. The prefix products live in the output array, which the problem does not count.

    Edge cases and common mistakes

    • One zero. {-1, 1, 0, -3, 3} gives {0, 0, 9, 0, 0}. Only the entry at the zero's position is non-zero. No special case is needed, because the products carry the zero along naturally.
    • Two zeros. {0, 0, 3} gives {0, 0, 0}: every product includes at least one zero.
    • Two elements. {2, 3} gives {3, 2}: each answer is the other element.
    • Negative numbers. {5, -2, 1} gives {-2, 5, -10}. The sign comes out right with no extra handling.
    • Updating suffix too early. Swapping the two lines in the second loop makes each answer include its own element.
    • Starting answer[0] at 0 or forgetting it. The default 0 makes the whole array zero.
    • Starting the first loop at 0. It would read answer[-1] and throw.

    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, 3} gives {0, 0, 0}.
    • {5, -2, 1} gives {-2, 5, -10}.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free