Product of Array Except Self

Medium

Topics
ArrayPrefix Sum

Given an integer array nums, return an array answer where answer[i] is the product of all elements except nums[i]. Do it without division.

Example 1

nums1234
answer241286
this cell is excludedthe product of all the others
Each answer cell is the product of every other value — the shaded pair shows that for index 0. Note the constraint the problem adds: division is not allowed, which rules out dividing the total product by each element, and that restriction is the whole point since a single zero would break it anyway.
Top row is the input; below it the answer for each position.
Input:  nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2

nums-110-33
answer00900
this cell is excludedthe product of all the others
Input:  nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints

  • 2 <= nums.length <= 10^5
  • Product fits in 32-bit integer.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The answer at index i is the product of everything to its left times everything to its right. Division would be easy but is disallowed (and breaks on zeros).

So compute prefix products in one pass and suffix products in another, multiplying them together.

Approach

  1. Left pass: ans[i] = product of all elements before i.
  2. Right pass: multiply ans[i] by the product of all elements after i.
  3. The output array doubles as scratch space, so no extra arrays are needed.

Walkthrough

nums = [1, 2, 3, 4]
prefix: [1, 1, 2, 6]
suffix multiply from right (24,12,4,1):
[1*24, 1*12, 2*4, 6*1] = [24, 12, 8, 6]

Complexity

  • Time — O(n): two linear passes.
  • Space — O(1): excluding the required output, just two running products.

Common Pitfalls

  • Do not use division — it fails when the array contains a zero.

Full Solution — all languages

class Solution:
    def productExceptSelf(self, nums):
        n = len(nums)
        out = [1] * n
        running = 1
        for i in range(n):
            out[i] = running
            running *= nums[i]
        running = 1
        for i in range(n - 1, -1, -1):
            out[i] *= running
            running *= nums[i]
        return out
SensAI
Beta
Tap the mic to stop voice mode