Power-Up Multipliers

Mediumprefix sumsAlso known as Product of Array Except Self

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

Before each turn the game must discard one card, and it shows, under every card, what the multiplier would be if that card were the one discarded. The game's scoring code only multiplies: dividing the full product by a card breaks as soon as a card is 0.

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

Without the 2: 3 × 4 × 5 = 60. Without the 3: 2 × 4 × 5 = 40. Without the 4: 2 × 3 × 5 = 30. Without the 5: 2 × 3 × 4 = 24.

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

Every product that keeps the 0 is 0. Only discarding the 0 itself gives something else: 3 × 2 × (-1) = -6. Dividing the full product (0) by 0 would crash 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, loop over all the other cards and multiply them together.

That is n − 1 multiplications for each of n positions, so O(n²). With 100,000 cards it is about 10 billion multiplications. Neighbouring answers share almost all their factors, and the brute force recomputes them every time. The division shortcut is O(n) but fails on zeros.

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