Everyone Else's Product

Medium · Arrays & Hashing · about 20 min

A team plays a scoring game where each player's bonus is the product of every other player's score. Given the scores in nums, return a list where position i holds the product of all numbers except nums[i].

  • Do it without division (scores can be 0, so dividing the total would break anyway).
  • The product of no numbers is 1, so a single player gets [1].
  • Scores can be negative or zero. Every answer fits in a normal integer.
  • nums has 0 to 100,000 numbers. Aim for O(n) time.

Example:

product_of_others([2, 3, 4, 5]) → [60, 40, 30, 24]

Hints

  • Split "everyone except me" into "everyone to my left" and "everyone to my right".
  • One pass from the left can store the left products; one pass from the right can multiply in the right products.
  • Start each running product at 1, and update it after you use it at each position.

Learn the pattern first: the Arrays & Hashing lesson.

More Arrays & Hashing problems