Problem 229460 · medium · Level 02 Linear Data Structures

Product of Everything Else

arrays · prefix products · suffix products

Given a list of integers nums, return a new list out where out[i] is the product of all elements of nums except nums[i]. Do not use division. For a single-element list the product of "everything else" is 1.

Examples

Input:  nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]

Input:  nums = [2, 0, 3]
Output: [0, 6, 0]

Constraints

  • 1 <= len(nums) <= 10**5
  • Every product fits in a Python int (inputs are small).
  • Return a new list; division is not allowed.
  • Target: O(n) time.

Goals

  • Combine a prefix pass and a suffix pass
  • Avoid division so zeros need no special handling
  • Stay linear without nested loops
Starting Python…