Ctrl K

Product of All the Others

Medium
You are given an integer array values. Build an array of the same length whose element at position i is the product of every element of values except values[i]. Division is off limits, and the solution must run in O(n). The product of any prefix and any suffix of values is guaranteed to fit in a signed 32-bit integer. Bonus: can you manage with O(1) extra memory, not counting the output?
Example 1
values=[2, 5, 3, 1] → [15, 6, 10, 30]

For index 0: 5 · 3 · 1 = 15; for index 1: 2 · 3 · 1 = 6, and so on.

Example 2
values=[4, 0, -2, 3] → [0, -24, 0, 0]

The zero sits at index 1, so only that position gets a non-zero answer: 4 · (-2) · 3 = -24.

Example 3
values=[-1, 7] → [7, -1]

Each element simply gets its only neighbour.

Constraints
  • 2 ≤ len(values) ≤ 10⁵
  • -30 ≤ values[i] ≤ 30
  • The product of every prefix and suffix fits in a signed 32-bit integer
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Stretch to the Goal MediumStudios for Recording Sessions MediumLongest Run with a Given Sum MediumBatch of Segment Adjustments MediumA Stretch Divisible by k Medium
loading Python…
Input
values=[2, 5, 3, 1]
Expected
[15, 6, 10, 30]

Run checks the first 3 tests in your browser. Submit checks all 63 tests on the server, hidden ones included.