Power-Up Multipliers

Mediumprefix sumsAlso known as Product of Array Except Self

In your card game, each player holds a row of power-up cards with multipliers: 3 triples your score, -1 flips it negative, 0 wipes it out. Your multiplier is all the cards multiplied together.

Before each turn the game discards one card, and under every card it shows the multiplier if that card were discarded. Dividing the full product by a card breaks as soon as a card is 0, so the scoring code only multiplies.

Your task

Write withoutEach(cards). Return a list out of the same length where out[i] is the product of every card except cards[i].

Do not use division. Aim for O(n) time.

withoutEach(cards: int[]) → int[]

Examples

Example 1
Input
cards = [2, 3, 4, 5]
Output
[60, 40, 30, 24]
Why

Discarding the 2 leaves 3 × 4 × 5 = 60, discarding the 3 leaves 2 × 4 × 5 = 40, discarding the 4 leaves 2 × 3 × 5 = 30, and discarding the 5 leaves 2 × 3 × 4 = 24.

Example 2
Input
cards = [3, 0, 2, -1]
Output
[0, -6, 0, 0]
Why

Every product that still contains the 0 is 0. Discarding the 0 gives 3 × 2 × (-1) = -6. Dividing the full product, which is 0, by the 0 card would fail here.

Constraints

  • 2 ≤ cards.length ≤ 100,000
  • -20 ≤ cards[i] ≤ 20
  • The product of all the non-zero cards fits in a 32-bit signed integer.
Start with brute force

For each position, multiply all the other cards together.

That takes O(n²) time, about 10 billion multiplications for 100,000 cards, because neighbouring answers share most of their factors and the brute force recomputes them each time. Dividing the full product by each card would be O(n), but it fails when a card is 0 and is not allowed here.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code