Skip to the code
cf.
+25 XP

#42 Scale Factor Without Itself

medium

A design tool stacks transforms, and each layer has a scale factor in factors. For a tooltip, you need, for each layer, the product of every other layer's factor.

Write scaleWithoutSelf(factors) that returns an array where item i is the product of all factors[j] with j !== i. Don't use division (factors can be 0), and aim for O(n) time.

Example 1

Input: factors = [2,3,4]
Output: [12,8,6]

3 * 4 = 12, 2 * 4 = 8, and 2 * 3 = 6.

Example 2

Input: factors = [5,0,2]
Output: [0,10,0]

Only the item at index 1 skips the 0, so only it is non-zero.

Constraints

  • 2 <= factors.length <= 10^5
  • -30 <= factors[i] <= 30
  • Every product fits in a safe integer.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).