Start learning free

LESSON 314 OF 667 · PARTIAL SUMS #1

Product of Array Except Self

Practice O(n)

You get a vector of integers nums.

Return a vector 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 vector doesn't count.

STEP 1 OF 9
    Ctrl + Enter to check