product-except-self.sh — zsh

Product of Array Except Self

medium
arraysprefix-sum

Return an array where output index i equals the product of every value in nums except nums[i]. Do not use division.

Input / output

  • Input: nums: integer[]
  • Output: integer[] of equal length

Examples

  1. [1,2,3,4] returns [24,12,8,6].
  2. [-1,1,0,-3,3] returns [0,0,9,0,0].

Constraints

  • 2 <= nums.length <= 100,000
  • Every prefix and suffix product fits a 32-bit signed integer

Follow-up Can you store suffix accumulation in one variable so output space is the only allocated array?

Examples
Example 1
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Example 3
Input: nums = [2,3]
Output: [3,2]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.