Show problems as
Classic problem #238MediumArrayPrefix Sum

Product of Array Except Self

Real-world version: Amplifier Bypass Gains
Tracked in this browser only
Read Product of Array Except Self on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A studio rack wires several amplifier stages in series. Stage i scales whatever signal reaches it by the integer factor gains[i]: a negative factor flips the signal's phase, and a factor of 0 means that stage is muted and kills the signal outright. The rack's overall factor is what you get by applying every stage in turn.

The engineer is auditioning patch cables, and for each stage wants to know the rack's overall factor when that single stage is jumpered out of the chain and all the other stages stay exactly as they are.

Given gains, return an array bypassed of the same length, where bypassed[i] is the factor the rack would have with stage i removed.

Your routine has to finish in linear time, and it may not use division anywhere: muted stages make dividing the rack's overall factor by a single stage's factor useless.

Examples

Example 1

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

Jumpering out the first stage leaves 1, 4 and 2, which combine to 8. Removing the second leaves 3 * 4 * 2 = 24, removing the third leaves 3 * 1 * 2 = 6, and removing the fourth leaves 3 * 1 * 4 = 12.

Example 2

Input
gains = [-2, 0, 5, 3]
Output
[0, -30, 0, 0]

Only removing the muted stage revives the rack, giving -2 * 5 * 3 = -30; every other chain still contains the muted stage and reads 0.

Example 3

Input
gains = [4, 0, 0, -6]
Output
[0, 0, 0, 0]

Two stages are muted, so whichever single stage is jumpered out a muted one is still in the chain and the rack stays silent.

Constraints

  • 2 <= gains.length <= 10^5
  • -30 <= gains[i] <= 30
  • Inputs are chosen so that every entry of the returned array fits in a signed 32-bit integer.
  • Division may not be used.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def bypass_gains(gains: list[int]) -> list[int]:
Java
public int[] bypassGains(int[] gains)